当手动生成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,]
这是允许的吗?
当前回答
尾随逗号在JavaScript中是允许的,但在IE中不允许。Douglas Crockford的无版本JSON规范不允许它们,因为它是无版本的,所以不应该改变。ES5 JSON规范允许它们作为扩展,但Crockford的RFC 4627不允许,ES5恢复为不允许。Firefox紧随其后。ie就是我们不能拥有美好事物的原因。
其他回答
PHP程序员可能需要检查implode()。它接受一个数组,使用字符串将其连接起来。
从医生那里…
$array = array('lastname', 'email', 'phone');
echo implode(",", $array); // lastname,email,phone
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);
String l = "[" + List<int>.generate(5, (i) => i + 1).join(",") + "]";
简单,便宜,易于阅读,并且无论规格如何都能正常工作。
$delimiter = '';
for .... {
print $delimiter.$whatever
$delimiter = ',';
}
对$delim的冗余赋值代价很小。 如果没有显式的循环,而是单独的代码片段,也同样有效。
不建议这样做,但您仍然可以执行类似这样的操作来解析它。
jsonStr = '[0,1,2,3,4,5,]'; 日期年份; eval('data = ' + jsonStr); 控制台.log(数据)