您可以在 JSON 对象中使用尾随逗号吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/201782/
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
Can you use a trailing comma in a JSON object?
提问by Ben Combee
When manually generating a JSON object or array, it's often easier to leave a trailing comma on the last item in the object or array. For example, code to output from an array of strings might look like (in a C++ like pseudocode):
手动生成 JSON 对象或数组时,通常更容易在对象或数组的最后一项上留下尾随逗号。例如,从字符串数组输出的代码可能看起来像(在类似 C++ 的伪代码中):
s.append("[");
for (i = 0; i < 5; ++i) {
s.appendF("\"%d\",", i);
}
s.append("]");
giving you a string like
给你一个字符串
[0,1,2,3,4,5,]
Is this allowed?
这是允许的吗?
采纳答案by brianb
Unfortunately the JSON specificationdoes not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.
不幸的是,JSON 规范不允许尾随逗号。有一些浏览器允许它,但通常您需要担心所有浏览器。
In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:
一般来说,我会尝试解决这个问题,并在实际值之前添加逗号,因此您最终会得到如下所示的代码:
s.append("[");
for (i = 0; i < 5; ++i) {
if (i) s.append(","); // add the comma only if this isn't the first entry
s.appendF("\"%d\"", i);
}
s.append("]");
That extra one line of code in your for loop is hardly expensive...
for 循环中额外的一行代码并不昂贵......
Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).
当从某种形式的字典向 JSON 输出结构时,我使用的另一种替代方法是始终在每个条目后附加一个逗号(如您在上面所做的那样),然后在末尾添加一个没有尾随逗号的虚拟条目(但是那只是懒惰;->)。
Doesn't work well with an array unfortunately.
不幸的是,不适用于数组。
回答by Ben Combee
No. The JSON spec, as maintained at http://json.org, does not allow trailing commas. From what I've seen, some parsers may silently allow them when reading a JSON string, while others will throw errors. For interoperability, you shouldn't include it.
不可以。在http://json.org维护的 JSON 规范不允许尾随逗号。据我所知,一些解析器在读取 JSON 字符串时可能会默默地允许它们,而其他解析器会抛出错误。为了互操作性,您不应该包含它。
The code above could be restructured, either to remove the trailing comma when adding the array terminator or to add the comma before items, skipping that for the first one.
上面的代码可以重构,要么在添加数组终止符时删除尾随逗号,要么在项目之前添加逗号,跳过第一个。
回答by Overflowee
Simple, cheap, easy to read, and always works regardless of the specs.
简单、便宜、易于阅读,并且无论规格如何都可以正常工作。
$delimiter = '';
for .... {
print $delimiter.$whatever
$delimiter = ',';
}
The redundant assignment to $delim is a very small price to pay. Also works just as well if there is no explicit loop but separate code fragments.
对 $delim 的冗余分配是一个非常小的代价。如果没有显式循环但单独的代码片段也能正常工作。
回答by Tobu
Trailing commas are allowed in JavaScript, but don't work in IE. Douglas Crockford's versionless JSON spec didn't allow them, and because it was versionless this wasn't supposed to change. The ES5 JSON spec allowed them as an extension, but Crockford's RFC 4627didn't, and ES5 reverted to disallowing them. Firefoxfollowed suit. Internet Explorer is why we can't have nice things.
尾随逗号在 JavaScript 中是允许的,但在 IE 中不起作用。Douglas Crockford 的无版本 JSON 规范不允许它们,因为它是无版本的,所以不应该改变。ES5 JSON 规范允许它们作为扩展,但 Crockford 的RFC 4627不允许,并且 ES5 恢复为禁止它们。Firefox紧随其后。Internet Explorer 是我们不能拥有美好事物的原因。
回答by Tobu
As it's been already said, JSON spec (based on ECMAScript 3) doesn't allow trailing comma. ES >= 5 allows it, so you can actually use that notation in pure JS. It's been argued about, and some parsers didsupport it (http://bolinfest.com/essays/json.html, http://whereswalden.com/2010/09/08/spidermonkey-json-change-trailing-commas-no-longer-accepted/), but it's the spec fact (as shown on http://json.org/) that it shouldn'twork in JSON. That thing said...
正如已经说过的,JSON 规范(基于 ECMAScript 3)不允许尾随逗号。ES >= 5 允许它,因此您实际上可以在纯 JS 中使用该符号。它被争论,有些解析器并支持它(http://bolinfest.com/essays/json.html,http://whereswalden.com/2010/09/08/spidermonkey-json-change-trailing-commas- no-longer-accepted/),但它不应该在 JSON 中工作是规范事实(如http://json.org/所示)。那件事说...
... I'm wondering why no-one pointed out that you can actually split the loop at 0th iteration and use leadingcomma instead of trailing one to get rid of the comparison code smell and any actual performance overhead in the loop, resulting in a code that's actually shorter, simpler and faster (due to no branching/conditionals in the loop) than other solutions proposed.
...我想知道为什么没有人指出您实际上可以在第 0 次迭代时拆分循环并使用前导逗号而不是尾随逗号来消除循环中的比较代码异味和任何实际性能开销,从而导致与其他提议的解决方案相比,该代码实际上更短、更简单、更快(由于循环中没有分支/条件)。
E.g. (in a C-style pseudocode similar to OP's proposed code):
例如(在类似于 OP 提议的代码的 C 风格伪代码中):
s.append("[");
// MAX == 5 here. if it's constant, you can inline it below and get rid of the comparison
if ( MAX > 0 ) {
s.appendF("\"%d\"", 0); // 0-th iteration
for( int i = 1; i < MAX; ++i ) {
s.appendF(",\"%d\"", i); // i-th iteration
}
}
s.append("]");
回答by Rik Heywood
回答by James Curran
Interestingly, both C & C++ (and I think C#, but I'm not sure) specifically allow the trailing comma -- for exactly the reason given: It make programmaticly generating lists much easier. Not sure why JavaScript didn't follow their lead.
有趣的是,C 和 C++(我认为是 C#,但我不确定)都特别允许尾随逗号 - 正是出于给出的原因:它使以编程方式生成列表变得更加容易。不知道为什么 JavaScript 没有跟随他们的脚步。
回答by user619271
Use JSON5. Don't use JSON.
使用 JSON5。不要使用 JSON。
- Objects and arrays can have trailing commas
- Object keys can be unquoted if they're valid identifiers
- Strings can be single-quoted
- Strings can be split across multiple lines
- Numbers can be hexadecimal (base 16)
- Numbers can begin or end with a (leading or trailing) decimal point.
- Numbers can include Infinity and -Infinity.
- Numbers can begin with an explicit plus (+) sign.
- Both inline (single-line) and block (multi-line) comments are allowed.
- 对象和数组可以有尾随逗号
- 如果对象键是有效标识符,则可以不加引号
- 字符串可以是单引号
- 字符串可以分成多行
- 数字可以是十六进制(基数为 16)
- 数字可以以(前导或尾随)小数点开头或结尾。
- 数字可以包括 Infinity 和 -Infinity。
- 数字可以以显式加号 (+) 开头。
- 允许行内(单行)和块(多行)注释。
回答by Zhang Boyang
There is a possible way to avoid a if-branch in the loop.
有一种可能的方法可以避免循环中出现 if 分支。
s.append("[ "); // there is a space after the left bracket
for (i = 0; i < 5; ++i) {
s.appendF("\"%d\",", i); // always add comma
}
s.back() = ']'; // modify last comma (or the space) to right bracket
回答by Timoty Weis
According to the Class JSONArray specification:
- An extra , (comma) may appear just before the closing bracket.
- The null value will be inserted when there is , (comma) elision.
- 一个额外的 ,(逗号)可能会出现在右括号之前。
- 有 ,(逗号)省略时将插入空值。
So, as I understand it, it should be allowed to write:
所以,据我所知,应该允许写:
[0,1,2,3,4,5,]
But it could happen that some parsers will return the 7 as item count (like IE8 as Daniel Earwicker pointed out) instead of the expected 6.
但是可能会发生一些解析器将 7 作为项目计数返回(如 Daniel Earwicker 指出的 IE8)而不是预期的 6。
Edited:
编辑:
I found this JSON Validatorthat validates a JSON string against RFC 4627(The application/json media type for JavaScript Object Notation) and against the JavaScript language specification. Actually here an array with a trailing comma is considered valid just for JavaScript and not for the RFC 4627 specification.
我发现这个JSON 验证器可以根据RFC 4627(JavaScript 对象表示法的应用程序/json 媒体类型)和 JavaScript 语言规范验证 JSON 字符串。实际上,这里带有尾随逗号的数组被认为仅对 JavaScript 有效,而不对 RFC 4627 规范有效。
However, in the RFC 4627 specification is stated that:
但是,在 RFC 4627 规范中声明:
2.3. Arrays
An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.
array = begin-array [ value *( value-separator value ) ] end-array
2.3. 数组
数组结构表示为围绕零个或多个值(或元素)的方括号。元素用逗号分隔。
array = begin-array [ value *( value-separator value ) ] end-array
To me this is again an interpretation problem. If you write that Elements are separated by commas(without stating something about special cases, like the last element), it could be understood in both ways.
对我来说,这又是一个解释问题。如果你写元素用逗号分隔(没有说明特殊情况,比如最后一个元素),它可以通过两种方式理解。
P.S. RFC 4627 isn't a standard (as explicitly stated), and is already obsolited by RFC 7159 (which is a proposed standard) RFC 7159
PS RFC 4627 不是标准(如明确说明的那样),并且已经被 RFC 7159(这是一个提议的标准)RFC 7159 废弃

