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

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

给你一个字符串

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

这是允许的吗?


当前回答

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格式化响应。

我通常循环遍历数组,并在字符串中的每个条目后附加一个逗号。循环结束后,我再次删除最后一个逗号。

也许不是最好的方法,但比每次检查它是否是循环中的最后一个对象要便宜一些。

不。https://json.org中的“铁路图”是规范的精确翻译,并明确表示a,总是在值之前,而不是直接在值之前]:

或}:

使用relax JSON,您可以使用后面的逗号,也可以不使用逗号。它们是可选的。

在解析类似json的文档时,完全没有必要使用逗号。

看一看relax JSON规范,你会发现原始JSON规范是多么“嘈杂”。太多的逗号和引号……

http://www.relaxedjson.org

您还可以使用这个在线RJSON解析器尝试您的示例,并查看它是否被正确解析。

http://www.relaxedjson.org/docs/converter.html?source=%5B0%2C1%2C2%2C3%2C4%2C5%2C%5D

如上所述,这是不允许的。但在JavaScript中,这是:

var a = Array()
for(let i=1; i<=5; i++) {
    a.push(i)
}
var s = "[" + a.join(",") + "]"

(在Firefox, Chrome, Edge, IE11中工作良好,并且在IE9, 8,7,5中没有let)