当手动生成JSON对象或数组时,通常更容易在对象或数组的最后一项上留下逗号。例如,从字符串数组输出的代码可能像这样(在c++中像伪代码):
s.append("[");
for (i = 0; i < 5; ++i) {
s.appendF("\"%d\",", i);
}
s.append("]");
给你一个字符串
[0,1,2,3,4,5,]
这是允许的吗?
当手动生成JSON对象或数组时,通常更容易在对象或数组的最后一项上留下逗号。例如,从字符串数组输出的代码可能像这样(在c++中像伪代码):
s.append("[");
for (i = 0; i < 5; ++i) {
s.appendF("\"%d\",", i);
}
s.append("]");
给你一个字符串
[0,1,2,3,4,5,]
这是允许的吗?
当前回答
简单,便宜,易于阅读,并且无论规格如何都能正常工作。
$delimiter = '';
for .... {
print $delimiter.$whatever
$delimiter = ',';
}
对$delim的冗余赋值代价很小。 如果没有显式的循环,而是单独的代码片段,也同样有效。
其他回答
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);
如上所述,这是不允许的。但在JavaScript中,这是:
var a = Array()
for(let i=1; i<=5; i++) {
a.push(i)
}
var s = "[" + a.join(",") + "]"
(在Firefox, Chrome, Edge, IE11中工作良好,并且在IE9, 8,7,5中没有let)
根据我过去的经验,我发现不同的浏览器对JSON中尾随逗号的处理方式不同。
Firefox和Chrome都处理得很好。但是IE(所有版本)似乎都坏了。我的意思是真正的中断,停止阅读剩余的剧本。
记住这一点,并且考虑到编写兼容的代码总是很好的事实,我建议花费额外的精力确保没有尾随逗号。
:)
有趣的是,C和c++(我认为还有c#,但我不确定)都特别允许后面有逗号——原因正是:它使以编程方式生成列表更容易。不知道为什么JavaScript没有效仿他们。
我不会参加辩论俱乐部,我会坚持防御性编程的原则,将两种简单的技术结合起来,以简化与他人的接口:
作为一个接收json数据的应用程序的开发者,我可以很轻松地允许后面有逗号。 当开发一个编写json的应用程序时,我会严格地使用其他答案的聪明技巧之一,只在项目之间添加逗号,并避免后面的逗号。
还有更大的问题需要解决……