17

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.

buddemat
  • 4,552
  • 14
  • 29
  • 49

2 Answers2

34

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
  • 60,510
  • 8
  • 78
  • 126
  • 4
    Where does it say the top structure must be an object? [This document](http://www.ietf.org/rfc/rfc4627.txt?number=4627) gives an example of just an array, and [json.org](http://json.org/) doesn't seem to specify this requirement. – Brendon Jul 15 '11 at 18:18
  • http://stackoverflow.com/a/4201631/977939 this has the explaination: reserve words. – jpillora Oct 22 '13 at 09:58
3

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
  • 2,132
  • 1
  • 13
  • 16