为什么我们需要在eval JSON中添加括号? [英] Why do we need to add parentheses to eval JSON?

查看:64
本文介绍了为什么我们需要在eval JSON中添加括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的代码需要为评估添加()?

Why does the following code needs to add ( and ) for eval?

var strJson = eval("(" + $("#status").val().replace(";","") + ")");

PS:$("#status").val()返回类似{"10000048":"1","25000175":"2","25000268":"3"};

推荐答案

eval采用JavaScript语句或表达式,但是{...}作为表达式有效,并且JavaScript的语法更喜欢陈述.

eval takes a JavaScript statement or expression, but {...} would be valid as a statement or an expression, and the grammar of JavaScript prefers a statement.

作为表达式:

{"10000048":"1","25000175":"2","25000268":"3"}

是具有某些属性(所需的属性)的对象.

is an Object with some properties (what you want).

作为一个语句,它是一个块:

As a statement, it is a block:

{                       // begin Block
    "10000048":         // LabelledStatement (but the quotes are invalid)
        "1",            // Expression, calculate string "1" then discard it, then
            "25000175": // you can't put a label inside an expression

出现错误.

(JavaScript标签可用于标记要与break/continue一起使用的特定语句.它们有点毫无意义,几乎从未使用过.)

(JavaScript labels can be used to label a particular statement for use with break/continue. They're a bit pointless and almost never used.)

因此,通过添加括号可以解决歧义.只有一个表达式可以以(开头,因此将在表达式上下文中解析内容,从而提供对象文字,而不是语句上下文.

So by adding the parentheses you resolve the ambiguity. Only an expression can start with (, so the contents are parsed in an expression context, giving an object literal, not a statement context.

偶然地,这不足以正确解释所有可能的JSON值.由于JSON设计上的疏忽,字符U + 2028和U + 2029(两个晦涩的Unicode行尾字符)可以有效地在JSON字符串文字中而不是JavaScript字符串文字中进行转义.如果您想安全起见,可以逃脱它们,例如:

Incidentally this is not quite enough to correctly interpret all possible JSON values. Due to an oversight in JSON's design, the characters U+2028 and U+2029, two obscure Unicode line-ending characters, are valid to put unescaped in a JSON string literal, but not in a JavaScript string literal. If you want to be safe, you can escape them, eg:

function parseJSON(s) {
    if ('JSON' in window) return JSON.parse(s);
    return eval('('+s.replace(/\u2028/g, '\\u2028').replace(/\u2029/g, '\\u2029')+')');
}

这篇关于为什么我们需要在eval JSON中添加括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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