JSON.parse意外令牌

shr*_*iek 39 javascript json

为什么每当我这样做: -

JSON.parse('"something"')
Run Code Online (Sandbox Code Playgroud)

它解析得很好,但是当我这样做时: -

var m = "something";
JSON.parse(m);
Run Code Online (Sandbox Code Playgroud)

它给我一个错误说: -

Unexpected token s
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 58

你要求它解析JSON文本something(不是"something").这是无效的JSON,字符串必须是双引号.

如果你想要第一个例子的等价物:

var s = '"something"';
var result = JSON.parse(s);
Run Code Online (Sandbox Code Playgroud)

  • 由于示例,将此标记为正确. (3认同)
  • @reabow:JavaScript允许单引号或双引号.JSON没有. (2认同)

Moa*_*han 16

在删除字符串的包装引号后,传递给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
Run Code Online (Sandbox Code Playgroud)

例子 -

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
Run Code Online (Sandbox Code Playgroud)

你可能想要看JSON.


pra*_*yer 6

变量(something)无效JSON,请使用http://jsonlint.com/进行验证