为什么在解析json字符串时,eval('('+ jsonString +')')的开放引号和括号 [英] Why the open quote and bracket for eval('(' + jsonString+ ')') when parsing json string
问题描述
请告诉我这种特定语法结构的原因
Can you please tell me the reason for this specific syntax structure
eval('(' + jsonString+ ')')
解析json文本时。 Crockford说文本必须用parens包装,以避免绊倒JavaScript的语法中的歧义。 此处。这是什么意思?
When parsing json text. Crockford says "The text must be wrapped in parens to avoid tripping on an ambiguity in JavaScript's syntax." here. What does that mean?
我们可以避免吗?
推荐答案
Crockford引用的语法歧义是,如果在表达式上下文中找不到打开的花括号,它将被识别为阻止,而不是像对象文字的开头。
The syntax ambiguity to which Crockford refers is that if an open curly brace is not found on expression context, it will be recognized like a block, and not like the start of an object literal.
例如:
{"foo": "bar"} // SyntaxError
会给你一个语法错误,因为它会被解释为一个块,带有字符串文字foo,以及令牌的意外用法 :
。
Will give you a syntax error, because it will be interpreted as a block, with a string literal "foo", and a unexpected usage of the token :
.
另一方面,括号,正式称为分组运算符,只能计算表达式,因此我们不会有任何语法歧义,因为只能在语句中预期一个块 c ontext。
On the other hand, the parentheses, formally called the grouping operator, can only evaluate expressions, therefore we will not have any syntax ambiguity because a block can only be expected on a statement context.
({"foo": "bar"})
编辑: @el.pescado 使得一个有趣的问题:
@el.pescado makes an interesting question:
你能解释为什么eval('{}')未定义?
Can you explain why eval('{}') is undefined?
ECMAScript描述了一种内部类型来解释语句的行为,它被称为完成规范类型。
ECMAScript describes an internal type to explain the behavior of statements, it's called The Completion Specification Type.
完成类型的值是形式的三元组(类型,值,目标)
,其中类型
可以正常
,中断
,继续
,返回
,或抛出
。
Values of the Completion type are triples of the form of (type, value, target)
, where type
can be normal
, break
, continue
, return
, or throw
.
value
可以是任何语言值或为空
,以及 TA rget
任何标识符或空
。
value
can be any language value or empty
, and target
any Identifier or empty
.
空块(生产 阻止:{}
)明确返回以下完成:
An empty block (the production Block : {}
) explicitly returns the following completion:
Return (normal, empty, empty).
eval
函数,执行代码并退出新创建的执行上下文后,检查结果完成评估的代码,在步骤7中我们可以看到,如果完成类型是正常
undefined >并且完成值为空
:
The eval
function, after executing the code, and exiting the newly created execution context, checks the result completion of the evaluated code, and in the Step 7 we can see that undefined
is explicitly returned if the completion type is normal
and the completion value is empty
:
...
...
7-如果result.type正常且其完成值为空,则返回值undefined。
7- If result.type is normal and its completion value is empty, then return the value undefined.
...
这篇关于为什么在解析json字符串时,eval('('+ jsonString +')')的开放引号和括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!