1

jQuery has altered it's implementation of $.parseJSON as of version 1.9.0 and we really depended on the way earlier versions of jQuery parsed null and empty strings, e.g. jQuery used to not throw an exception and would return a null value for null and empty string.

We would like to utilize the newest version of jQuery which at the time of writing is 1.9.1, but replace the implementation of $.parseJSON.

Documentation stating the change from jQuery: http://api.jquery.com/jQuery.parseJSON/

Is there some JavaScript we could use to tell jQuery to replace it's "natural" version of the $.parseJSON function with another implementation / function with the same name...the version from jQuery 1.8.3?

http://code.jquery.com/jquery-1.8.3.js has the function's implementation that we need.

4

3 回答 3

3

如果必须,请这样做:

jQuery._parseJSON = jQuery.parseJSON;

jQuery.parseJSON = function( data ) {

    if ( !data || typeof data !== "string") {
        return null;
    }

    return jQuery._parseJSON( data );

}
于 2013-03-27T03:58:00.803 回答
2

我不会推荐它,但如果你仍然想这样做

创建一个 jquery-override.js 文件并将以下内容添加到其中

jQuery.parseJSON = function( data ) {
        if ( !data || typeof data !== "string") {
            return null;
        }

        // Make sure leading/trailing whitespace is removed (IE can't handle it)
        data = jQuery.trim( data );

        // Attempt to parse using the native JSON parser first
        if ( window.JSON && window.JSON.parse ) {
            return window.JSON.parse( data );
        }

        // Make sure the incoming data is actual JSON
        // Logic borrowed from http://json.org/json2.js
        if ( rvalidchars.test( data.replace( rvalidescape, "@" )
            .replace( rvalidtokens, "]" )
            .replace( rvalidbraces, "")) ) {

            return ( new Function( "return " + data ) )();

        }
        jQuery.error( "Invalid JSON: " + data );
    }

然后在 jquery-1.9.1.js 文件之后包含这个文件

于 2013-03-27T03:49:44.923 回答
0

如果您的问题与在 jQuery 的$.ajax()方法的上下文中发生的$.parseJSON()调用有关,那么这里是一个不错的解决方案。您可以通过设置如下转换器来覆盖从 JSON 字符串到 JS 对象的默认转换:

$.ajaxSetup({ 
            converters: { "text json": function (jsonString) {
                var jsonObj = mySpecialParsingMethod(jsonString);
                return jsonObj;
            } }
});

如果您没有就 $.ajax() 方法问这个问题......那么没关系。:-)

于 2014-01-29T20:51:51.140 回答