AGENDA
jQuery.parseJSON() VS.Json.parse
Json.stringify
Json.parse
The JSON.parse() method parses a string as JSON, optionally transforming the value produced by parsing.
- Where the browser provides native implementation of JSON.parse, jQuery uses it to parse the string.
- JSON.parse() is natively available on some browsers, not on others, so it's safer to use a library.
- It's safer to use the jQuery method because some browsers do not have any JSON functionalities natively.
- It's all about compatibility, just like you use jQuery's each method instead of the array's native forEach method for iteration.
jQuery.parseJSON()
versus
Json.parse
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 );
},
jQuery.parseJSON checks if JSON.parse is supported by browser, it so it will use JSON.parse, else jQuery.parse will use it's own code to parse a string into JSON.
Video
jquery-parsejson-vs-json-parse
JSON.stringify
The JSON.stringify() method converts a value to JSON, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
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" ] }
VIDEO DEMO
jQuery & Json
By eunjoolee787
jQuery & Json
- 1,138