javascript - 是否有任何实际理由为 JSON 键使用带引号的字符串?

标签 javascript json browser double-quotes

根据 Crockford 的 json.org ,一个 JSON object 是由 members 组成的,它是由 pairs 组成的。

每一对都由一个string和一个value组成,其中一个string被定义为:

A string is a sequence of zero or more Unicode characters, wrapped in double quotes, using backslash escapes. A character is represented as a single character string. A string is very much like a C or Java string.

但实际上大多数程序员甚至不知道 JSON 键应该用双引号括起来,因为大多数浏览器不需要使用双引号。

用双引号将 JSON 括起来有意义吗?

有效示例:

{
  "keyName" : 34
}

相对于无效:

{
   keyName : 34
}

最佳答案

为什么 JSON 键应该用引号括起来的真正原因取决于 ECMAScript 3 标识符的语义。

Reserved words不能在没有引号的对象文字中用作属性名称,例如:

({function: 0}) // SyntaxError
({if: 0}) // SyntaxError
({true: 0}) // SyntaxError
// etc...

如果使用引号,则属性名称有效:

({"function": 0}) // Ok
({"if": 0}) // Ok
({"true": 0}) // Ok

自己的 Crockford 在 this talk 中进行了解释,他们希望保持 JSON 标准简单,并且不希望对其进行所有这些语义限制:

....

That was when we discovered the unquoted name problem. It turns out ECMA Script 3 has a whack reserved word policy. Reserved words must be quoted in the key position, which is really a nuisance. When I got around to formulizing this into a standard, I didn't want to have to put all of the reserved words in the standard, because it would look really stupid.

At the time, I was trying to convince people: yeah, you can write applications in JavaScript, it's actually going to work and it's a good language. I didn't want to say, then, at the same time: and look at this really stupid thing they did! So I decided, instead, let's just quote the keys.
That way, we don't have to tell anybody about how whack it is.

That's why, to this day, keys are quoted in JSON.

...

ECMAScript 第 5 版标准修复了这个问题,现在在 ES5 实现中,在对象字面量和成员访问(obj.function ES5 中的 Ok)中,即使保留字也可以不带引号使用。

仅作记录,该标准最近由软件 vendor 实现,您可以在此 compatibility table 上查看哪些浏览器包含此功能(参见作为属性名称的保留字)

关于javascript - 是否有任何实际理由为 JSON 键使用带引号的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4201441/

相关文章:

javascript - 使用node.js将非常大的json文件索引/摄取到数据库

javascript - 如何使用Backbone解析JSON?

java - 如何使用 GSON 将空字符串视为空对象?

javascript - 我们可以使用 jquery 启用浏览器位置吗

javascript - 如何使用nodejs/express将数据存储在mongodb中?

javascript - 多次应用一种方法,有更好的方法吗?

c# - 反序列化 JSON 时出错无法将 JSON 对象反序列化为类型 'System.String'

php - 嵌套的 while 循环不起作用,而是显示意外的 '}'

http - DELETE 和 PUT HTTP 动词现在适用于所有浏览器?

javascript 文件结构 - 任何好的解决方案?