Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.parseJSON() returns null on valid object

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?

like image 430
Sherzod Avatar asked Dec 25 '11 22:12

Sherzod


2 Answers

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.

like image 99
outis Avatar answered Oct 09 '22 14:10

outis


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/

like image 39
Andrew Odri Avatar answered Oct 09 '22 12:10

Andrew Odri