JSON.parse 意外令牌
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18791718/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JSON.parse unexpected token s
提问by shriek
Why is it that whenever I do :-
为什么每当我这样做:-
JSON.parse('"something"')
it just parses fine but when I do:-
它只是解析得很好,但是当我这样做时:-
var m = "something";
JSON.parse(m);
it gives me an error saying:-
它给了我一个错误说:-
Unexpected token s
回答by T.J. Crowder
You're asking it to parse the JSON text something(not "something"). That's invalid JSON, strings must be in double quotes.
您要求它解析 JSON 文本something(不是"something")。这是无效的 JSON,字符串必须用双引号括起来。
If you want an equivalent to your first example:
如果你想要一个相当于你的第一个例子:
var s = '"something"';
var result = JSON.parse(s);
回答by Moazzam Khan
What you are passing to JSON.parse method must be a valid JSON after removing the wrapping quotes for string.
在删除字符串的包装引号后,您传递给 JSON.parse 方法的内容必须是有效的 JSON。
so somethingis not a valid JSON but "something"is.
sosomething不是有效的 JSON,但"something"确实如此。
A valid JSON is -
有效的 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
Examples -
例子 -
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
You may want to look JSON.
你可能想看看JSON。
回答by prayerslayer
Variables (something) are not valid JSON, verify using http://jsonlint.com/
变量 ( something) 不是有效的 JSON,请使用http://jsonlint.com/ 进行验证
回答by Quentin
Because JSON has a string data type (which is practically anything between "and "). It does not have a data type that matches something
因为 JSON 具有字符串数据类型(实际上介于"和之间")。它没有匹配的数据类型something
回答by hoogw
valid json string must have double quote.
有效的 json 字符串必须有双引号。
JSON.parse({"u1":1000,"u2":1100}) // will be ok
no quote cause error
没有报价导致错误
JSON.parse({u1:1000,u2:1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
single quote cause error
单引号导致错误
JSON.parse({'u1':1000,'u2':1100})
// error Uncaught SyntaxError: Unexpected token u in JSON at position 2
You must valid json string at https://jsonlint.com
您必须在https://jsonlint.com 上提供有效的 json 字符串

