Add jQuery.parseJSON in jQuery 1.3

Is it possible to extend jQuery 1.3 to include a function parseJSONfrom 1.4.1+, and does it work the same way as in jQuery 1.4.1+? How can i do this?

I have some sites where I have to use jQuery 1.3, but I have a tool that requires parseJSON, which was introduced only in jQuery 1.4.1. I vaguely know that I should take parseJSON from 1.4.1+ and try to make it a plugin, but I don’t know how to do it.

+3
source share
3 answers

You can make this plugin as follows:

$.extend({
    error: function( msg ) { throw msg; },
    parseJSON: function( data ) {
        if ( typeof data !== "string" || !data ) {
            return null;
        }    
        data = jQuery.trim( data );    
        if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
            .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
            .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {    
            return window.JSON && window.JSON.parse ?
                window.JSON.parse( data ) :
                (new Function("return " + data))();    
        } else {
            jQuery.error( "Invalid JSON: " + data );
        }
    }
});

.
jQuery 1.4.4 - . jQuery 1.3, , $.parseJSON(), ... , , $.parseJSON() .

+11

, 1.3? jQuery.json $.toJSON $.evalJSON, 1.4. JSON.parse JSON.stringify , . JSON2, JSON.parse JSON.stringify .

0
source

Source: https://habr.com/ru/post/1779071/


All Articles