Does JSON.parse() require double quoting?

冷暖自知 提交于 2021-02-07 04:57:37

问题


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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/883243/does-json-parse-require-double-quoting

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!