js中的奇怪的JSON解析行为,“Unexpected token:” [英] Weird JSON parsing behavior in js, "Unexpected token :"

查看:758
本文介绍了js中的奇怪的JSON解析行为,“Unexpected token:”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此jsfiddle 所示,如果您有一个JS文件并且创建了一个没有JSON对象的JSON对象使用它时,它的行为会有所不同,具体取决于键(成员)是否用引号括起来。

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.

有效代码: {a:1} ;

无效代码: {a:1};

你会得到的是一条错误信息(在Chrome中,与FF / IE不同,但语法仍然失败)

What you will get is an error message (in Chrome, different for FF/IE, but still fails on syntax)


未捕获的SyntaxError:意外的标记:

Uncaught SyntaxError: Unexpected token :

但是如果以某种方式使用该对象,例如: alert( {a:1}); 一切都好了。

but if you use the object in some way, for example: alert({ "a": 1 }); everything is OK again.

为什么会这样?

推荐答案

声明:

{ a: 1 };

对象文字。它是一个块语句,其中包含一个带标签的表达式。这是有效的。

is not an object literal. It's a block statement with one labeled expression in it. It's valid.

这个:

{ "a": 1 };

是语法错误,因为它只是不可解析。引用的a在块内部启动一个表达式语句,但是在字符串之后的下一个标记是冒号,并且没有表达式形式看起来像一个表达式后面跟一个冒号。

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.

现在:

var x = { "a": 1 };

有效,因为{不会被解释为块语句的开头。该语句以 var 开头,因此它是一个变量声明。在=标记右侧的表达式中,{唯一可以表示的是对象文字的开头。同样,请注意:

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:

({ "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.

这篇关于js中的奇怪的JSON解析行为,“Unexpected token:”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆