当手动生成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,]
这是允许的吗?
当前回答
由于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
其他回答
我不会参加辩论俱乐部,我会坚持防御性编程的原则,将两种简单的技术结合起来,以简化与他人的接口:
作为一个接收json数据的应用程序的开发者,我可以很轻松地允许后面有逗号。 当开发一个编写json的应用程序时,我会严格地使用其他答案的聪明技巧之一,只在项目之间添加逗号,并避免后面的逗号。
还有更大的问题需要解决……
由于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
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);
有一种可能的方法可以避免循环中的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
我通常循环遍历数组,并在字符串中的每个条目后附加一个逗号。循环结束后,我再次删除最后一个逗号。
也许不是最好的方法,但比每次检查它是否是循环中的最后一个对象要便宜一些。