Javascript 在 JSON 中,为什么每个名称都被引用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2067974/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
in JSON, Why is each name quoted?
提问by Cheeso
The JSON specsays that JSON is an object or an array. In the case of an object,
JSON 规范说 JSON 是一个对象或一个数组。在对象的情况下,
An object structure is represented as a pair of curly brackets surrounding zero or more name/value pairs (or members). A name is a string....
对象结构表示为一对大括号,围绕零个或多个名称/值对(或成员)。 名称是一个字符串。...
And later, the spec says that a string is surrounded in quotes.
后来,规范说字符串用引号括起来。
Why?
为什么?
Thus,
因此,
{"Property1":"Value1","Property2":18}
and not
并不是
{Property1:"Value1",Property2:18}
Question 1: why not allow the name in the name/value pairs to be unquoted identifiers?
问题 1:为什么不允许名称/值对中的名称是不带引号的标识符?
Question 2: Is there a semantic difference between the two representations above, when evaluated in Javascript?
问题 2:在 Javascript 中评估时,上述两种表示之间是否存在语义差异?
采纳答案by Quentin
Question 1: why not allow the name in the name/value pairs to be unquoted identifiers?
问题 1:为什么不允许名称/值对中的名称是不带引号的标识符?
The design philosophy of JSON is "Keep it simple"
JSON 的设计理念是“保持简单”
"Quote names with ""is a lot simpler than "You may quote names with "or 'but you don't have to, unless they contain certain characters (or combinations of characters that would make it a keyword) and 'or "may need to be quoted depending on what delimiter you selected".
“有报价的名字"”是一个简单了很多比“你可能引述其名称"或',但你不必,除非它们包含某些字符(或字符,将使其成为一个关键词的组合),并'或"可能需要根据被引用在您选择的分隔符上”。
Question 2: Is there a semantic difference between the two representations above, when evaluated in Javascript?
问题 2:在 Javascript 中评估时,上述两种表示之间是否存在语义差异?
No. In JavaScript they are identical.
不。在 JavaScript 中,它们是相同的。
回答by CMS
I leave a quote from a presentation that Douglas Crockford (the creator of the JSON standard) gave to Yahoo.
我引用了 Douglas Crockford(JSON 标准的创建者)给雅虎的演讲中的一句话。
He talks about how he discoveredJSON, and amongst other things why he decided to use quoted keys:
他谈到了他是如何发现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.
.... 那是我们发现未引用名称问题的时候。事实证明,ECMA Script 3 有一个 whack 保留字策略。保留字必须在关键位置引用,这真的很麻烦。当我着手将其制定为标准时,我不想将所有保留字都放在标准中,因为这看起来非常愚蠢。
当时,我试图说服人们:是的,你可以用 JavaScript 编写应用程序,它实际上可以工作,而且它是一种很好的语言。然后,我不想同时说:看看他们所做的这件非常愚蠢的事情!所以我决定,相反,让我们只引用键。
这样,我们就不必告诉任何人它有多糟糕。这就是为什么直到今天,键都在 JSON 中引用。
You can find the complete video and transcript here.
您可以在此处找到完整的视频和文字记录。
回答by michael herndon
In javascript objects can be used like a hash/hashtable with key pairs.
在 javascript 中,对象可以像带有密钥对的散列/散列表一样使用。
However if your key has characters that javascript could not tokenize as a name, it would fail when trying it access like a property on an object rather than a key.
但是,如果您的密钥具有 javascript 无法标记为名称的字符,则在尝试像对象上的属性而不是密钥一样访问它时,它会失败。
var test = {};
test["key"] = 1;
test["#my-div"] = "<div> stuff </div>";
// test = { "key": 1, "#my-div": "<div> stuff </div>" };
console.log(test.key); // should be 1
console.log(test["key"]); // should be 1
console.log(test["#my-div"]); // should be "<div> stuff </div>";
console.log(test.#my-div); // would not work.
identifiers can sometimes have characters that can not be evaluated as a token/identifier in javascript, thus its best to put all identifiers in strings for consistency.
标识符有时可能包含无法在 javascript 中被评估为标记/标识符的字符,因此最好将所有标识符放在字符串中以保持一致性。
回答by Anon.
Both :and whitespace are permitted in identifiers. Without the quotes, this would cause ambiguity when trying to determine what exactly constitutes the identifier.
这两个:和空白被允许在标识符。如果没有引号,则在尝试确定标识符的确切构成时会导致歧义。
回答by Dave Scotese
I think the right answer to Cheeso's question is that the implementation surpassed the documentation. It no longer requires a string as the key, but rather something else, which can either be a string (ie quoted) or (probably) anything that can be used as a variable name, which I will guess means start with a letter, _, or $, and include only letters, numbers, and the $ and _.
我认为 Cheeso 问题的正确答案是实现超越了文档。它不再需要一个字符串作为键,而是需要其他东西,它可以是一个字符串(即引用)或(可能)任何可以用作变量名的东西,我猜这意味着以字母开头,_ , 或 $,并且仅包含字母、数字以及 $ 和 _。
I wanted to simplify the rest for the next person who visits this question with the same idea I did. Here's the meat:
我想为下一个以我所做的相同想法访问此问题的人简化其余部分。这是肉:
Variable names are not interpolated in JSON when used as an object key(Thanks Friedo!)
当用作对象键时,变量名不会插入到 JSON 中(感谢 Friedo!)
Breton, using "identifier" instead of "key", wrote that "if an identifier happens to be a reserved word, it is interpreted as that word rather than as an identifier." This may be true, but I tried it without any trouble:
Breton 使用“标识符”而不是“键”,写道“如果标识符恰好是保留字,则将其解释为该词而不是标识符。” 这可能是真的,但我没有任何问题地尝试过:
var a = {do:1,long:2,super:3,abstract:4,var:5,break:6,boolean:7};
a.break
=> 6
=> 6
About using quotes, Quentin wrote "...but you don't have to, unless [the key] contains certain characters(or combinations of characters that would make it a keyword)"
关于使用引号,Quentin 写道:“...但您不必这样做,除非 [key] 包含某些字符(或使其成为关键字的字符组合)”
I found the former part (certain characters) is true, using the @ sign (in fact, I think $ and _ are the only characters that don't cause the error):
我发现前一部分(某些字符)是正确的,使用 @ 符号(实际上,我认为 $ 和 _ 是唯一不会导致错误的字符):
var a = {a@b:1};
=> Syntax error
=> 语法错误
var a = {"a@b":1};
a['a@b']
=> 1
=> 1
but the parenthetical about keywords, as I showed above, isn't true.
但正如我上面所展示的,关于关键字的括号是不正确的。
What I wanted works because the text between the opening { and the colon, or between the comma and the colon for subsequent properties is used as an unquoted string to make an object key, or, as Friedo put it, a variable name there doesn't get interpolated:
我想要的是有效的,因为开头 { 和冒号之间的文本,或后续属性的逗号和冒号之间的文本用作未加引号的字符串来创建对象键,或者,正如 Friedo 所说,那里的变量名没有' t 被插值:
var uid = getUID();
var token = getToken(); // Returns ABC123
var data = {uid:uid,token:token};
data.token
=> ABC123
=> ABC123
回答by shashank joshi
It may reduce data size if quotes on name are only allowed when necessary
如果仅在必要时才允许在名称上使用引号,则可能会减少数据大小
回答by Dave Archer
If json describes objects, then in practise you get the following
如果 json 描述对象,那么在实践中你会得到以下内容
var foo = {};
var bar = 1;
foo["bar"] = "hello";
foo[bar] = "goodbye";
so then,
那么,
foo.bar == "hello";
foo[1] == "goodbye" // in setting it used the value of var bar
so even if your examples do produce the same result, their equivalents in "raw code" wouldn't. Maybe that's why?? dunno, just an idea.
因此,即使您的示例确实产生了相同的结果,它们在“原始代码”中的等价物也不会。也许这就是为什么?不知道,只是一个想法。

