当手动生成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,]
这是允许的吗?
当前回答
有一种可能的方法可以避免循环中的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
其他回答
String l = "[" + List<int>.generate(5, (i) => i + 1).join(",") + "]";
不幸的是,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时,我使用的另一种替代方法是始终在每个条目后面附加一个逗号(正如您上面所做的那样),然后在末尾添加一个没有逗号的虚拟条目(但这只是懒惰;->)。
不幸的是,它不能很好地使用数组。
我通常循环遍历数组,并在字符串中的每个条目后附加一个逗号。循环结束后,我再次删除最后一个逗号。
也许不是最好的方法,但比每次检查它是否是循环中的最后一个对象要便宜一些。
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);
使用JSON5。不要使用JSON。
对象和数组可以以逗号结尾 如果对象键是有效的标识符,则可以不加引号 字符串可以使用单引号 字符串可以被分割成多行 数字可以是十六进制(以16为基数) 数字可以以小数点(前导或后导)开始或结束。 数字可以包括∞和-∞。 数字可以以显式的加号(+)开头。 内联(单行)和块(多行)注释都是允许的。
http://json5.org/
https://github.com/aseemk/json5