views:

655

answers:

2

I'm using Firefox 3.5b4.

This alerts [object Object],[object Object]:

var jsonString = '[{"foo": "one", "bar": 1}, {"foo": "two", "bar": 2}]';
var jsonObjects = JSON.parse(jsonString);
alert(jsonObjects);

This alerts an empty string, i.e. jsonObjects is null.

var jsonString = "[{'foo': '1', 'bar': 2}, {'foo': '3', 'bar': 4}]";
var jsonObjects = JSON.parse(jsonString);
alert(jsonObjects);

Likewise for unquoted property names, i.e. {foo: '1', bar: 2}.

What's going on? Am I missing something obvious, or is there a rule about double and single quoting with JSON.parse? All three versions work OK with eval.

+8  A: 

The JSON standard mandates double quotes.

Remember that JSON isn't just "write a JS object". It's a very strict syntax that happens to be also readable as a JS object. Not every JS-valid syntax is valid JSON. In fact, your example ins't really valid JSON, since it's an array of objects while the standard specifies that the top construct MUST be an object.

Of course, most JSON parsers are more flexible, allowing for non-standard options (like single quotes); but don't rely on that.

Javier
A: 

To add to what Javier said, JSON limits the format mainly for security reasons (so functions can't be called, etc.). If you're not concerned about security, use javascript's "eval()" function to convert the string to an object.

kbosak
Don't use eval if you plan on using this code in an add-on though.
sdwilsh