当手动生成JSON对象或数组时,通常更容易在对象或数组的最后一项上留下逗号。例如,从字符串数组输出的代码可能像这样(在c++中像伪代码):

s.append("[");
for (i = 0; i < 5; ++i) {
    s.appendF("\"%d\",", i);
}
s.append("]");

给你一个字符串

[0,1,2,3,4,5,]

这是允许的吗?


当前回答

String l = "[" + List<int>.generate(5, (i) => i + 1).join(",") + "]";

其他回答

我不会参加辩论俱乐部,我会坚持防御性编程的原则,将两种简单的技术结合起来,以简化与他人的接口:

作为一个接收json数据的应用程序的开发者,我可以很轻松地允许后面有逗号。 当开发一个编写json的应用程序时,我会严格地使用其他答案的聪明技巧之一,只在项目之间添加逗号,并避免后面的逗号。

还有更大的问题需要解决……

使用JSON5。不要使用JSON。

对象和数组可以以逗号结尾 如果对象键是有效的标识符,则可以不加引号 字符串可以使用单引号 字符串可以被分割成多行 数字可以是十六进制(以16为基数) 数字可以以小数点(前导或后导)开始或结束。 数字可以包括∞和-∞。 数字可以以显式的加号(+)开头。 内联(单行)和块(多行)注释都是允许的。

http://json5.org/

https://github.com/aseemk/json5

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);

我保持当前的计数,并将其与总计数进行比较。如果当前计数小于总计数,则显示逗号。

如果在执行JSON生成之前没有总计数,则可能无法工作。

同样,如果您使用的是PHP 5.2.0或更高版本,则可以使用内置的JSON API格式化响应。