3

Is it possible to extend jQuery 1.3 to include the parseJSON function from 1.4.1+, and have it function the same way as it does in jQuery 1.4.1+? How would I go about that?

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

Yahel
  • 37,023
  • 22
  • 103
  • 153

3 Answers3

11

You could make it a plugin like this:

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

You can test it here.
This code's adopted from jQuery 1.4.4 - found here. After including the above with jQuery 1.3 as your question has, just use $.parseJSON() as you normally would...or in your case, just include the plugins after the above code and $.parseJSON() will be present for them to use.

Yahel
  • 37,023
  • 22
  • 103
  • 153
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 2
    Only one slight issue if you are using 1.3.x ... jQuery.error wasn't added until 1.4.1 :) Adding: - error: function( msg ) { throw msg; }, above the parseJSON definition will fix that though. – mr_urf Nov 29 '11 at 14:20
1

You could use Crockfords implementation: https://github.com/douglascrockford/JSON-js

Or here, for a direct link: https://github.com/douglascrockford/JSON-js/blob/master/json_parse.js

Jakob
  • 24,154
  • 8
  • 46
  • 57
0

Is it impossible for you to edit the code that uses 1.3? The jQuery.json plugin provides $.toJSON and $.evalJSON, which are equivalent to the new ones from 1.4. You could try to use the native JSON.parse and JSON.stringify in browsers where it's supported. In older browser you'll need to include JSON2 to add JSON.parse and JSON.stringify support to these browsers.

Jesper Haug Karsrud
  • 1,193
  • 6
  • 10
  • No, its unfortunately not possible. My hands are tied on the contents of the code I'm receiving from this plugin. – Yahel Dec 07 '10 at 22:47