The advantage for this method is that it is safe to use the jQuery method because some older browsers do not have any JSON functionalities natively.
The JSON library has the advantage that it has a method to turn a JavaScript object into a JSON string, which jQuery does not currently support.
It is all about compatibility, just like you use jQuery's each method instead of the array's native forEach method for iteration.
...
if (JSON.parse) {
return JSON.parse(data);
} else {
return jQuery.parseJSON(data);
}
...
jQuery.parseJSON
versus
JSON.parse
jQuery.parseJSON checks if JSON.parse is supported by the browser, if so it will use JSON.parse, else jQuery.parse will use it's own code to parse a string into JSON.
parseJSON: function( data ) {
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
if ( data === null ) {
return data;
}
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
if ( 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 );
},
stackoverflow.com
jQuery.parseJSON
versus
JSON.parse
TESTER RUNNER
jQuery.parseJSON
versus
JSON.parse
http://jsperf.com/jquery-parsejson-vs-json-parse
var contact = new Object();
contact.firstname = "Jesper";
contact.surname = "Aaberg";
contact.phone = ["555-0100", "555-0120"];
var memberfilter = new Array();
memberfilter[0] = "surname";
memberfilter[1] = "phone";
var jsonText = JSON.stringify(contact, memberfilter, "\t");
document.write(jsonText);
// Output:
// { "surname": "Aaberg", "phone": [ "555-0100", "555-0120" ] }
JSON.stringify
http://msdn.microsoft.com/
JSON.stringify({}); // '{}'
JSON.stringify(true); // 'true'
JSON.stringify("foo"); // '"foo"'
JSON.stringify([1, "false", false]); // '[1,"false",false]'
JSON.stringify({ x: 5 }); // '{"x":5}'
Examples:
var JavascriptObject = {name: "George", lastname: "Batalinski"};
var ValidJSON = JSON.stringify({name: "George", lastname: "Batalinski"});
JSON.stringify({x: 5, y: 6});
// '{"x":5,"y":6}' or '{"y":6,"x":5}'
JSON.stringify([new Number(1), new String("false"), new Boolean(false)]);
// '[1,"false",false]'
// Symbols:
JSON.stringify({x: undefined, y: Object, z: Symbol("")});
// '{}'
JSON.stringify({[Symbol("foo")]: "foo"});
// '{}'
JSON.stringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]);
// '{}'
JSON.stringify({[Symbol.for("foo")]: "foo"}, function (k, v) {
if (typeof k === "symbol"){
return "a symbol";
}
});
// '{}'
JSON.stringify
Mozilla Developer Network