当手动生成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,]
这是允许的吗?
当前回答
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);
其他回答
不。https://json.org中的“铁路图”是规范的精确翻译,并明确表示a,总是在值之前,而不是直接在值之前]:
或}:
由于for循环用于遍历数组或类似的可迭代数据结构,我们可以使用数组的长度,如下所示,
awk -v header="FirstName,LastName,DOB" '
BEGIN {
FS = ",";
print("[");
columns = split(header, column_names, ",");
}
{ print(" {");
for (i = 1; i < columns; i++) {
printf(" \"%s\":\"%s\",\n", column_names[i], $(i));
}
printf(" \"%s\":\"%s\"\n", column_names[i], $(i));
print(" }");
}
END { print("]"); } ' datafile.txt
datafile.txt包含,
Angela,Baker,2010-05-23
Betty,Crockett,1990-12-07
David,Done,2003-10-31
String l = "[" + List<int>.generate(5, (i) => i + 1).join(",") + "]";
根据我过去的经验,我发现不同的浏览器对JSON中尾随逗号的处理方式不同。
Firefox和Chrome都处理得很好。但是IE(所有版本)似乎都坏了。我的意思是真正的中断,停止阅读剩余的剧本。
记住这一点,并且考虑到编写兼容的代码总是很好的事实,我建议花费额外的精力确保没有尾随逗号。
:)
使用JSON5。不要使用JSON。
对象和数组可以以逗号结尾 如果对象键是有效的标识符,则可以不加引号 字符串可以使用单引号 字符串可以被分割成多行 数字可以是十六进制(以16为基数) 数字可以以小数点(前导或后导)开始或结束。 数字可以包括∞和-∞。 数字可以以显式的加号(+)开头。 内联(单行)和块(多行)注释都是允许的。
http://json5.org/
https://github.com/aseemk/json5