gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 12:42:51 27 4
gpt4 key购买 nike

根据 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com