Can you use a trailing comma in a JSON object?

2019-01-01 10:13发布

When manually generating a JSON object or array, it's often easier to leave a trailing comma on the last item in the object or array. For example, code to output from an array of strings might look like (in a C++ like pseudocode):

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?

15条回答
浅入江南
2楼-- · 2019-01-01 10:53

Trailing commas are allowed in JavaScript, but don't work in IE. Douglas Crockford's versionless JSON spec didn't allow them, and because it was versionless this wasn't supposed to change. The ES5 JSON spec allowed them as an extension, but Crockford's RFC 4627 didn't, and ES5 reverted to disallowing them. Firefox followed suit. Internet Explorer is why we can't have nice things.

查看更多
牵手、夕阳
3楼-- · 2019-01-01 10:53

From my past experience, I found that different browsers deal with trailing commas in JSON differently.

Both Firefox and Chrome handles it just fine. But IE (All versions) seems to break. I mean really break and stop reading the rest of the script.

Keeping that in mind, and also the fact that it's always nice to write compliant code, I suggest spending the extra effort of making sure that there's no trailing comma.

:)

查看更多
初与友歌
4楼-- · 2019-01-01 10:53

I keep a current count and compare it to a total count. If the current count is less than the total count, I display the comma.

May not work if you don't have a total count prior to executing the JSON generation.

Then again, if your using PHP 5.2.0 or better, you can just format your response using the JSON API built in.

查看更多
笑指拈花
5楼-- · 2019-01-01 10:53

It is not recommended, but you can still do something like this to parse it.

jsonStr = '[0,1,2,3,4,5,]';
let data;
eval('data = ' + jsonStr);
console.log(data)

查看更多
浅入江南
6楼-- · 2019-01-01 10:53

There is a possible way to avoid a if-branch in the loop.

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
查看更多
人气声优
7楼-- · 2019-01-01 10:55

I usually loop over the array and attach a comma after every entry in the string. After the loop I delete the last comma again.

Maybe not the best way, but less expensive than checking every time if it's the last object in the loop I guess.

查看更多
登录 后发表回答