为什么每当我这样做时: -
JSON.parse('"something"')
它解析得很好,但是当我这样做时: -
var m = "something";
JSON.parse(m);
它给我一个错误说: -
Unexpected token s
答案 0 :(得分:56)
您要求它解析JSON文本something
(不是"something"
)。这是无效的JSON,字符串必须是双引号。
如果你想要第一个例子的等价物:
var s = '"something"';
var result = JSON.parse(s);
答案 1 :(得分:15)
在删除字符串的包装引号后,传递给JSON.parse方法的内容必须是有效的JSON。
因此something
不是有效的JSON,"something"
是。
有效的JSON是 -
JSON = null
/* boolean literal */
or true or false
/* A JavaScript Number Leading zeroes are prohibited; a decimal point must be followed by at least one digit.*/
or JSONNumber
/* Only a limited sets of characters may be escaped; certain control characters are prohibited; the Unicode line separator (U+2028) and paragraph separator (U+2029) characters are permitted; strings must be double-quoted.*/
or JSONString
/* Property names must be double-quoted strings; trailing commas are forbidden. */
or JSONObject
or JSONArray
示例 -
JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
JSON.parse("'foo'"); // error since string should be wrapped by double quotes
您可能希望查看JSON。
答案 2 :(得分:6)
变量(something
)无效JSON,请使用http://jsonlint.com/进行验证
答案 3 :(得分:1)
因为JSON有一个字符串数据类型(实际上是"
和"
之间的任何内容)。它没有与something
答案 4 :(得分:1)
有效的json字符串必须有双引号。
JSON.parse({"u1":1000,"u2":1100}) // will be ok
没有报价导致错误
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
单引号导致错误
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
处有效的json字符串