当手动生成JSON对象或数组时,通常更容易在对象或数组的最后一项上留下逗号。例如,从字符串数组输出的代码可能像这样(在c++中像伪代码):

s.append("[");
for (i = 0; i < 5; ++i) {
    s.appendF("\"%d\",", i);
}
s.append("]");

给你一个字符串

[0,1,2,3,4,5,]

这是允许的吗?


当前回答

Using a trailing comma is not allowed for json. A solution I like, which you could do if you're not writing for an external recipient but for your own project, is to just strip (or replace by whitespace) the trailing comma on the receiving end before feeding it to the json parser. I do this for the trailing comma in the outermost json object. The convenient thing is then if you add an object at the end, you don't have to add a comma to the now second last object. This also makes for cleaner diffs if your config file is in a version control system, since it will only show the lines of the stuff you actually added.

    char* str = readFile("myConfig.json");
    char* chr = strrchr(str, '}') - 1;
    int i = 0;
    while( chr[i] == ' ' || chr[i] == '\n' ){
        i--;
    }
    if( chr[i] == ',' ) chr[i] = ' ';
    JsonParser parser;
    parser.parse(str);

其他回答

有趣的是,C和c++(我认为还有c#,但我不确定)都特别允许后面有逗号——原因正是:它使以编程方式生成列表更容易。不知道为什么JavaScript没有效仿他们。

不幸的是,JSON规范不允许后面有逗号。有一些浏览器允许这样做,但通常需要考虑所有浏览器。

一般来说,我试图把问题转过来,在实际值之前添加逗号,所以你最终得到的代码看起来像这样:

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("]");

在for循环中额外的一行代码并不昂贵……

当从某种形式的字典中将结构输出到JSON时,我使用的另一种替代方法是始终在每个条目后面附加一个逗号(正如您上面所做的那样),然后在末尾添加一个没有逗号的虚拟条目(但这只是懒惰;->)。

不幸的是,它不能很好地使用数组。

有一种可能的方法可以避免循环中的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

如前所述,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/),但这是规范事实(如http://json.org/所示),它不应该在JSON中工作。那东西说……

... 我想知道为什么没有人指出你可以在第0次迭代时分割循环,并使用前导逗号而不是尾随逗号来摆脱比较代码的味道和循环中的任何实际性能开销,从而导致代码比其他提出的解决方案更短、更简单、更快(由于循环中没有分支/条件)。

例如(在c风格的伪代码中,类似于OP的建议代码):

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("]");

我不会参加辩论俱乐部,我会坚持防御性编程的原则,将两种简单的技术结合起来,以简化与他人的接口:

作为一个接收json数据的应用程序的开发者,我可以很轻松地允许后面有逗号。 当开发一个编写json的应用程序时,我会严格地使用其他答案的聪明技巧之一,只在项目之间添加逗号,并避免后面的逗号。

还有更大的问题需要解决……