简体   繁体   English

JavaScript 解析函数 JSON.parse 未按预期工作

[英]JavaScript parse function JSON.parse does not work as expected

The case:案子:

var s = '{"a": 2}';
var d = JSON.parse(s); // d = Object {a: 2}

It is OK.没关系。

The similar case does not parse string, however.然而,类似的情况不解析字符串。 Why?为什么?

var s = "{'a': 2}";

var d= JSON.parse(s) // Uncaught SyntaxError: Unexpected token ' in JSON at position 1

Expected result - parsed object like in the first case.预期结果 - 像第一种情况一样解析对象。 It should have worked because ' and " are interchangeable in javascript.它应该有效,因为 ' 和 " 在 javascript 中可以互换。

根据标准,你需要双引号来表示一个字符串,它是一个键。

It should have worked because ' and " are interchangeable in javascript.它应该有效,因为 ' 和 " 在 javascript 中可以互换。

JSON is not JavaScript. JSON 不是 JavaScript。

JSON strings must be delimited with quotation marks, not apostrophes. JSON 字符串必须用引号分隔,而不是撇号。

See the specification :规格

A string begins and ends with quotation marks.字符串以引号开始和结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM