How To Replace jQuery 1.9.1's $.parseJSON function with the implementation from jQuery 1.8.3

StackOverflow https://stackoverflow.com/questions/15651471

  •  29-03-2022
  •  | 
  •  

Pregunta

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.

¿Fue útil?

Solución

If you must, do it this way:

jQuery._parseJSON = jQuery.parseJSON;

jQuery.parseJSON = function( data ) {

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

    return jQuery._parseJSON( data );

}

Otros consejos

I wouldn't recommend it, but if you still want to do it

create a jquery-override.js file and add the below contents to it

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 );
    }

Then include this file after jquery-1.9.1.js file

If your question is related to the $.parseJSON() call that occurs in the context of jQuery's $.ajax() method, then here is a nice solution. You can override the default conversion from JSON String to JS Object by setting up a converter like so:

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

If you are not asking this question in regard to the $.ajax() method.....then nevermind. :-)

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top