$ .parseJSON () returns null in the actual object

jsfiddle link

var x = {
    "Item1" : 1,
    "Item2" : {
        "Item3" : 3
    }
}

   alert(JSON.stringify(x, undefined, 2));
   alert($.parseJSON(x));

The first warns the actual object. The second warns zero. In real code, the variable "x" can be a string or an object, so I have to parse both types. Did I miss something?

+5
source share
2 answers

You are parsing an object. You are parsing strings, not objects; jQuery.parseJSONtakes only lines. From the documentation:

jQuery.parseJSON (json) <For> json JSON string to parse. For>

Using:

if (! window.console) {
    console = {
        log: function (msg) {
            alert(msg);
        }
    };
}

console.log($.parseJSON(JSON.stringify(x, undefined, 2)));

Standard jQuery does not seem to contain string JSON. Generally, jQuery handles this for you, so this is optional. If you need it, there are different plugins.

+9

:

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););

, , .

: http://jsfiddle.net/uaN8G/

+2

All Articles