I've learned (the hard way) that I need to add parentheses around JSON data, like this:

stuff = eval('(' + data_from_the_wire + ')');
// where data_from_the_wire was, for example {"text": "hello"}

(In Firefox 3, at least).

What's the reason behind this? I hate writing code without understanding what´s behind the hood.

推荐答案

将括号放在data_from_the_wire左右实际上相当于

stuff = eval('return ' + data_from_the_wire + ';');

If you were to eval without the parentheses, then the code would be evaluated, and if you did have any named functions inside it those would be defined, but not returned.

以创建函数时调用函数的能力为例:

(function() { alert('whoot'); })()

Will call the function that has just been defined. The following, however, does not work:

function() { alert('whoot'); }()

因此,我们看到括号有效地将代码转换为返回的表达式,而不仅仅是要运行的代码.

Json相关问答推荐

您可以使用Jolt对JSON执行OR条件吗

如何在数组抖动中按值分组

如何在Gatsby/Reaction中获取JSON-File子 node

解析JSON说函数parse_json不存在?

如何在PowerShell中访问嵌套的JSON字段

Pandas 对REST API的自定义响应

如何用JQ打印JSON文件的路径和键值

如何使用jq使用子值对象的键对json对象进行分组

将JSON行转换为TSV格式, for each 数组项生成单独的行

使用 jolt 将对象数组转换为数组

我如何将 JSON 格式与 flutter 一起使用?帮助使用 Gamebanana api

使用 BASH 和 JQ 我想将 json 文件与 bash 数组进行比较

UTF-8 字符编码之战 json_encode()

Json.NET SerializeObject 转义值以防止 XSS

Jackson 没有使用 @JsonProperty 覆盖 Getter

错误未判断调用put(K, V)作为原始类型java.util.HashMap的成员

如何在 Django JSONField 数据上聚合(最小/最大等)?

在 JSON.NET 中序列化派生类时的字段顺序

通过 JSON 发送 64 位值的公认方式是什么?

Backbone.js 模型与集合