Is there any practical reason to use quoted strings for JSON keys?
根据Crockford的json.org,JSON对象由成员组成,成员由成对组成。
每对由字符串和值组成,字符串定义为:
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是否有意义?
有效示例:
1 2 3 | { "keyName" : 34 } |
与无效相反:
1 2 3 | { keyName : 34 } |
关于为什么JSON键应该在引号中的真正原因依赖于ECMAScript 3的标识符的语义。
保留字不能用作没有引号的Object Literals中的属性名称,例如:
1 2 3 4 | ({function: 0}) // SyntaxError ({if: 0}) // SyntaxError ({true: 0}) // SyntaxError // etc... |
如果使用引号,则属性名称有效:
1 2 3 | ({"function": 0}) // Ok ({"if": 0}) // Ok ({"true": 0}) // Ok |
自己的Crockford在本次演讲中解释了这一点,他们希望将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实现中,甚至可以在没有引号的情况下使用保留字,包括对象文字和成员访问(ES5中的
仅仅是为了记录,软件供应商最近正在实施此标准,您可以在此兼容性表中查看哪些浏览器包含此功能(请参阅保留字作为属性名称)
是的,它是无效的JSON,并且在许多情况下会被拒绝,例如jQuery 1.4+有一个检查,使得不带引号的JSON无声地失败。为什么不合规?
让我们再看一个例子:
1 2 3 | { myKey:"value" } { my-Key:"value" } { my-Key[]:"value" } |
...所有这些都是有效的引号,为什么不一致并在所有情况下使用它们,消除问题的可能性?
Web开发人员世界中的一个更常见的例子:在大多数浏览器中有成千上万的无效HTML示例......这是否会减少调试或维护的痛苦?完全没有,恰恰相反。
另外@Matthew在下面的评论中提出了最好的观点,这已经失败,不带引号的键会在所有主流浏览器(以及其他正确实现它的其他浏览器)中使用
YAML实际上是JSON的超集,它支持您想要做的事情。虽然它是一个超集,它可以让你保持它想要的简单。
YAML是一股清新的空气,值得您花时间去看看它。最佳起点是:http://en.wikipedia.org/wiki/YAML
在阳光下有各种语言的库,包括JS,例如https://github.com/nodeca/js-yaml