I was looking for the method to do jQuery.parseJSON in JavaScript that parses a json to return a JavaScript object. I can't use jQuery since the whole plugin that I have built is standalone JS and no jQuery has been used till now. Is there something of this sort that's already provided in JavaScript?
-
@KevinB : Editted the question. I intended to mention jQuery.parseJSONuser1240679– user12406792013-02-27 18:51:08 +00:00Commented Feb 27, 2013 at 18:51
-
My comment still applies.user400654– user4006542013-02-27 18:52:17 +00:00Commented Feb 27, 2013 at 18:52
3 Answers
Use the native JSON object (this is the only time it is correct to say "JSON object", it is literally an object named JSON) to manipulate JSON strings.
https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON
Use JSON.parse(yourJSONString); to serialize and JSON.stringify(yourJSONObject); to deserialize.
If you look at the jQuery core source on line 492, jQuery.parseJSON is just an alias to JSON.parse.
1 Comment
jbabey Editted the question. I intended to mention jQuery.parseJSONYou can either use the native JSON object, which is supported in most browsers, but you will run into an issue when you try to use it in the dinosaur browsers such as IE7 and lower. There is the option to include a standalone plugin that mimics native functionality here (JSON.js).
Comments
Short answer:
Use the browser native method JSON.parse()
window.JSON.parse(jsonString);
Long answer:
To get it working in old browsers, you can take the source code of jQuery.parseJSON and remove any dependencies on jQuery itself. Here is a working standalone version:
function standaloneParseJson ( 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;
}
var rvalidchars = /^[\],:{}\s]*$/;
var rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g;
var rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g;
var rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g;
if ( typeof data === "string" ) {
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = data.replace(/^\s+|\s+$/g, '');
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 ) )();
}
}
}
// Error code here
//jQuery.error( "Invalid JSON: " + data );
}