手动生成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?
手动生成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?
Unfortunately the JSON specification does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.
一般来说,我会try 扭转这个问题,在实际值之前加上逗号,所以最终的代码如下所示:
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...
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 ;->).
不幸的是,它不能很好地处理array.