Using jQuery 1.4.4 and JSON2.js in the same project

Say I were to make use of the jQuery framework but also use some JSON features that may utilize JSON2.js. I know that jQuery had some built in features for JSON, but JSON2.js adds functions like JSON.stringify for older clients.

With that in mind, should JSON2.js be loaded before jQuery or vise versa? Will jQuery detect the enhancements of JSON2.js as its being loaded or does it not matter in the order of loading them?

It doesn’t matter in which order they are loaded. They won’t know anything about each other.

It’s a good idea to keep JSON2 around, to provide JSON support to older web browsers that don’t have native support.

The reason I asked is because jQuery will look for native browser support for JSON.parse but if JSON2.js is loaded before jQuery, does it create a JSON.parse function and jQuery then treats that as a native browser function instead of having to do eval()?

Looking at the code can help with those questions.


if (typeof JSON.parse !== 'function') {
    JSON.parse = function (text, reviver) {

Spelled out the above is: If there is no JSON.parse function, create one.

// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
	window.JSON.parse( data ) :
	(new Function("return " + data))();

Spelled out the above is: If there is a JSON.parse function (it doesn’t matter the origin), use that one. If not, parse it internally.

Thanks for your help. Although you didn’t give me a direct answer as to which library to load first, I have a hunch you are telling me to load JSON2.js first to ensure compatibility.

If I didn’t have JSON2.js and jQuery 1.4.4 were to eval() for non native browsers, which library (JSON2.js or jQuery) would you say is more secure and accurate for JSON.parse?

The previous post stated:

It doesn’t matter in which order they are loaded. They won’t know anything about each other.

My direct answer to “which library to load first” is that is does not matter. Take your pick on the order that you like, as things will continue to work properly regardless of the order in which they are loaded.

JSON2 is better because that one explicitly decodes the data. In other words, the ability to exploit the JSON2 code is virtually nil. The ability to exploit the jQuery parse technique is less well known.