jsfiddle link
var x = {
"Item1" : 1,
"Item2" : {
"Item3" : 3
}
}
alert(JSON.stringify(x, undefined, 2));
alert($.parseJSON(x));
First one alerts valid object. The second one alerts null. In the real code, the "x" variable can be string or an object, so I should be able to parse both types. Am I missing something?
You're parsing an object. You parse strings, not objects; jQuery.parseJSON
only takes strings. From the documentation:
jQuery.parseJSON( json )
- json
- The JSON string to parse.
Usage:
if (! window.console) {
console = {
log: function (msg) {
alert(msg);
}
};
}
console.log($.parseJSON(JSON.stringify(x, undefined, 2)));
Standard jQuery doesn't appear to have a JSON stringifier. Typically, jQuery handles that for you, so it isn't necessary. If you need it, there are various plugins.
Try this:
var x = { "Item1" : 1, "Item2" : { "Item3" : 3 }};
var stringified = JSON.stringify(x, undefined, 2);
var objectified = $.parseJSON(stringified);
alert(stringified);
alert(objectified.Item1);
alert(JSON.stringify(objectified, undefined, 2););
As mentioned above, this will give the parser a string to parse into an object, not the object itself.
Here is a fiddle: http://jsfiddle.net/uaN8G/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With