Can you use a trailing comma in a JSON object? Can you use a trailing comma in a JSON object? json json

Can you use a trailing comma in a JSON object?

Unfortunately the JSON specification does not allow a trailing comma. There are a few browsers that will allow it, but generally you need to worry about all browsers.

In general I try turn the problem around, and add the comma before the actual value, so you end up with code that looks like this:

s.append("[");for (i = 0; i < 5; ++i) {  if (i) s.append(","); // add the comma only if this isn't the first entry  s.appendF("\"%d\"", i);}s.append("]");

That extra one line of code in your for loop is hardly expensive...

Another alternative I've used when output a structure to JSON from a dictionary of some form is to always append a comma after each entry (as you are doing above) and then add a dummy entry at the end that has not trailing comma (but that is just lazy ;->).

Doesn't work well with an array unfortunately.

No. The JSON spec, as maintained at, does not allow trailing commas. From what I've seen, some parsers may silently allow them when reading a JSON string, while others will throw errors. For interoperability, you shouldn't include it.

The code above could be restructured, either to remove the trailing comma when adding the array terminator or to add the comma before items, skipping that for the first one.

Simple, cheap, easy to read, and always works regardless of the specs.

$delimiter = '';for ....  {    print $delimiter.$whatever    $delimiter = ',';}

The redundant assignment to $delim is a very small price to pay.Also works just as well if there is no explicit loop but separate code fragments.