Javascript js 中奇怪的 JSON 解析行为,“意外令牌:”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10080551/
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
Weird JSON parsing behavior in js, "Unexpected token :"
提问by karnyj
As demonstrated in this jsfiddle, if you have a JS file and you create a JSON object without using it, it behaves differently depending on whether the keys(members) are wrapped in quotes or not.
如本 jsfiddle 所示,如果您有一个 JS 文件并且您在不使用它的情况下创建了一个 JSON 对象,则根据键(成员)是否用引号括起来,它的行为会有所不同。
valid code:{ a: 1};
invalid code: { "a": 1 };
有效代码:{ a: 1};
无效代码:{ "a": 1 };
What you will get is an error message (in Chrome, different for FF/IE, but still fails on syntax)
您将得到一条错误消息(在 Chrome 中,FF/IE 不同,但语法仍然失败)
Uncaught SyntaxError: Unexpected token :
未捕获的语法错误:意外标记:
but if you use the object in some way, for example: alert({ "a": 1 });
everything is OK again.
但是,如果您以某种方式使用该对象,例如:alert({ "a": 1 });
一切正常。
Why does this happen?
为什么会发生这种情况?
回答by Pointy
The statement:
该声明:
{ a: 1 };
is notan object literal. It's a block statement with one labeled expression in it. It's valid.
是不是一个对象常量。这是一个块语句,其中包含一个带标签的表达式。这是有效的。
This:
这个:
{ "a": 1 };
is a syntax error because it's just not parseable. The quoted "a" starts an expression statement inside the block, but then the next token after the string is a colon, and there's no expression form that looks like an expression followed by a colon.
是语法错误,因为它无法解析。带引号的“a”在块内开始一个表达式语句,但是字符串后面的下一个标记是一个冒号,并且没有表达式形式看起来像一个表达式后跟一个冒号。
Now:
现在:
var x = { "a": 1 };
works because the "{" is not interpreted as the start of a block statement. That statement starts with var
, so it's a variable declaration. Within the expression on the right side of the "=" token, the only thing that a "{" can mean is the start of an object literal. Similarly, note that:
之所以有效,是因为“{”不被解释为块语句的开始。该语句以 开头var
,因此它是一个变量声明。在“=”标记右侧的表达式中,“{”的唯一含义是对象字面量的开始。同样,请注意:
({ "a": 1 });
is OK because the opening parenthesis makes the parser expect a nested subexpression, so again the "{" unambiguously means that it's the start of an object literal.
没问题,因为左括号使解析器期望嵌套子表达式,因此“{”再次明确表示它是对象文字的开始。
回答by SCBuergel.eth
I just realized than when loading the JSON via require
and the filename does not end on .json
i get this error. Renaming the file to bla.json
and it works fine.
我刚刚意识到,当通过加载 JSONrequire
并且文件名没有以.json
我收到此错误时。将文件重命名为bla.json
,它工作正常。
回答by ColossalChris
This error can popup when doing a jQuery AJAX call using jsonp
when jsonp
is not necessary. Try switching your data type on your AJAX call if this is the case to normal json
当不需要使用jsonp
when执行 jQuery AJAX 调用时,可能会弹出此错误jsonp
。如果这是正常情况,请尝试在 AJAX 调用中切换数据类型json
$.ajax({
dataType: 'json', // try using json rather than json p
...
});