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

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?

This question is related to json syntax delimiter

The answer is


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.


Rather than engage in a debating club, I would apply Defensive Programming. As a developer of an app that receives json data, I'd allow the trailing comma. When developing an app that writes json, I'd use one of the clever techniques of the other answers to only add commas between items. There are bigger problems to be solved...


As stated it is not allowed. But in JavaScript this is:

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

(works fine in Firefox, Chrome, Edge, IE11, and without the let in IE9, 8, 7, 5)


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.


Interestingly, both C & C++ (and I think C#, but I'm not sure) specifically allow the trailing comma -- for exactly the reason given: It make programmaticly generating lists much easier. Not sure why JavaScript didn't follow their lead.


No. The JSON spec, as maintained at http://json.org, 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.


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.

:)


Interestingly, both C & C++ (and I think C#, but I'm not sure) specifically allow the trailing comma -- for exactly the reason given: It make programmaticly generating lists much easier. Not sure why JavaScript didn't follow their lead.


No. The "railroad diagrams" in https://json.org are an exact translation of the spec and make it clear a , always comes before a value, never directly before ]:

railroad diagram for array

or }:

railroad diagram for object


As stated it is not allowed. But in JavaScript this is:

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

(works fine in Firefox, Chrome, Edge, IE11, and without the let in IE9, 8, 7, 5)


According to the Class JSONArray specification:

  • An extra , (comma) may appear just before the closing bracket.
  • The null value will be inserted when there is , (comma) elision.

So, as I understand it, it should be allowed to write:

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

But it could happen that some parsers will return the 7 as item count (like IE8 as Daniel Earwicker pointed out) instead of the expected 6.


Edited:

I found this JSON Validator that validates a JSON string against RFC 4627 (The application/json media type for JavaScript Object Notation) and against the JavaScript language specification. Actually here an array with a trailing comma is considered valid just for JavaScript and not for the RFC 4627 specification.

However, in the RFC 4627 specification is stated that:

2.3. Arrays

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

To me this is again an interpretation problem. If you write that Elements are separated by commas (without stating something about special cases, like the last element), it could be understood in both ways.

P.S. RFC 4627 isn't a standard (as explicitly stated), and is already obsolited by RFC 7159 (which is a proposed standard) RFC 7159


Use JSON5. Don't use JSON.

  • Objects and arrays can have trailing commas
  • Object keys can be unquoted if they're valid identifiers
  • Strings can be single-quoted
  • Strings can be split across multiple lines
  • Numbers can be hexadecimal (base 16)
  • Numbers can begin or end with a (leading or trailing) decimal point.
  • Numbers can include Infinity and -Infinity.
  • Numbers can begin with an explicit plus (+) sign.
  • Both inline (single-line) and block (multi-line) comments are allowed.

http://json5.org/

https://github.com/aseemk/json5


No. The JSON spec, as maintained at http://json.org, 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.


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

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


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.


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.


As it's been already said, JSON spec (based on ECMAScript 3) doesn't allow trailing comma. ES >= 5 allows it, so you can actually use that notation in pure JS. It's been argued about, and some parsers did support it (http://bolinfest.com/essays/json.html, http://whereswalden.com/2010/09/08/spidermonkey-json-change-trailing-commas-no-longer-accepted/), but it's the spec fact (as shown on http://json.org/) that it shouldn't work in JSON. That thing said...

... I'm wondering why no-one pointed out that you can actually split the loop at 0th iteration and use leading comma instead of trailing one to get rid of the comparison code smell and any actual performance overhead in the loop, resulting in a code that's actually shorter, simpler and faster (due to no branching/conditionals in the loop) than other solutions proposed.

E.g. (in a C-style pseudocode similar to OP's proposed code):

s.append("[");
// MAX == 5 here. if it's constant, you can inline it below and get rid of the comparison
if ( MAX > 0 ) {
    s.appendF("\"%d\"", 0); // 0-th iteration
    for( int i = 1; i < MAX; ++i ) {
        s.appendF(",\"%d\"", i); // i-th iteration
    }
}
s.append("]");

Since a for-loop is used to iterate over an array, or similar iterable data structure, we can use the length of the array as shown,

awk -v header="FirstName,LastName,DOB" '
  BEGIN {
    FS = ",";
    print("[");
    columns = split(header, column_names, ",");
  }
  { print("  {");
    for (i = 1; i < columns; i++) {
      printf("    \"%s\":\"%s\",\n", column_names[i], $(i));
    }
    printf("    \"%s\":\"%s\"\n", column_names[i], $(i));
    print("  }");
  }
  END { print("]"); } ' datafile.txt

With datafile.txt containing,

 Angela,Baker,2010-05-23
 Betty,Crockett,1990-12-07
 David,Done,2003-10-31

No. The "railroad diagrams" in https://json.org are an exact translation of the spec and make it clear a , always comes before a value, never directly before ]:

railroad diagram for array

or }:

railroad diagram for object


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.


No. The JSON spec, as maintained at http://json.org, 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.


PHP coders may want to check out implode(). This takes an array joins it up using a string.

From the docs...

$array = array('lastname', 'email', 'phone');
echo implode(",", $array); // lastname,email,phone

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.


Rather than engage in a debating club, I would apply Defensive Programming. As a developer of an app that receives json data, I'd allow the trailing comma. When developing an app that writes json, I'd use one of the clever techniques of the other answers to only add commas between items. There are bigger problems to be solved...


According to the Class JSONArray specification:

  • An extra , (comma) may appear just before the closing bracket.
  • The null value will be inserted when there is , (comma) elision.

So, as I understand it, it should be allowed to write:

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

But it could happen that some parsers will return the 7 as item count (like IE8 as Daniel Earwicker pointed out) instead of the expected 6.


Edited:

I found this JSON Validator that validates a JSON string against RFC 4627 (The application/json media type for JavaScript Object Notation) and against the JavaScript language specification. Actually here an array with a trailing comma is considered valid just for JavaScript and not for the RFC 4627 specification.

However, in the RFC 4627 specification is stated that:

2.3. Arrays

An array structure is represented as square brackets surrounding zero or more values (or elements). Elements are separated by commas.

array = begin-array [ value *( value-separator value ) ] end-array

To me this is again an interpretation problem. If you write that Elements are separated by commas (without stating something about special cases, like the last element), it could be understood in both ways.

P.S. RFC 4627 isn't a standard (as explicitly stated), and is already obsolited by RFC 7159 (which is a proposed standard) RFC 7159


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.

:)


With Relaxed JSON, you can have trailing commas, or just leave the commas out. They are optional.

There is no reason at all commas need to be present to parse a JSON-like document.

Take a look at the Relaxed JSON spec and you will see how 'noisy' the original JSON spec is. Way too many commas and quotes...

http://www.relaxedjson.org

You can also try out your example using this online RJSON parser and see it get parsed correctly.

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


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.


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

Since a for-loop is used to iterate over an array, or similar iterable data structure, we can use the length of the array as shown,

awk -v header="FirstName,LastName,DOB" '
  BEGIN {
    FS = ",";
    print("[");
    columns = split(header, column_names, ",");
  }
  { print("  {");
    for (i = 1; i < columns; i++) {
      printf("    \"%s\":\"%s\",\n", column_names[i], $(i));
    }
    printf("    \"%s\":\"%s\"\n", column_names[i], $(i));
    print("  }");
  }
  END { print("]"); } ' datafile.txt

With datafile.txt containing,

 Angela,Baker,2010-05-23
 Betty,Crockett,1990-12-07
 David,Done,2003-10-31

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.


PHP coders may want to check out implode(). This takes an array joins it up using a string.

From the docs...

$array = array('lastname', 'email', 'phone');
echo implode(",", $array); // lastname,email,phone

Use JSON5. Don't use JSON.

  • Objects and arrays can have trailing commas
  • Object keys can be unquoted if they're valid identifiers
  • Strings can be single-quoted
  • Strings can be split across multiple lines
  • Numbers can be hexadecimal (base 16)
  • Numbers can begin or end with a (leading or trailing) decimal point.
  • Numbers can include Infinity and -Infinity.
  • Numbers can begin with an explicit plus (+) sign.
  • Both inline (single-line) and block (multi-line) comments are allowed.

http://json5.org/

https://github.com/aseemk/json5


Interestingly, both C & C++ (and I think C#, but I'm not sure) specifically allow the trailing comma -- for exactly the reason given: It make programmaticly generating lists much easier. Not sure why JavaScript didn't follow their lead.


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.


PHP coders may want to check out implode(). This takes an array joins it up using a string.

From the docs...

$array = array('lastname', 'email', 'phone');
echo implode(",", $array); // lastname,email,phone

Interestingly, both C & C++ (and I think C#, but I'm not sure) specifically allow the trailing comma -- for exactly the reason given: It make programmaticly generating lists much easier. Not sure why JavaScript didn't follow their lead.


With Relaxed JSON, you can have trailing commas, or just leave the commas out. They are optional.

There is no reason at all commas need to be present to parse a JSON-like document.

Take a look at the Relaxed JSON spec and you will see how 'noisy' the original JSON spec is. Way too many commas and quotes...

http://www.relaxedjson.org

You can also try out your example using this online RJSON parser and see it get parsed correctly.

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


PHP coders may want to check out implode(). This takes an array joins it up using a string.

From the docs...

$array = array('lastname', 'email', 'phone');
echo implode(",", $array); // lastname,email,phone

No. The JSON spec, as maintained at http://json.org, 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.


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

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

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


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.


Examples related to json

Use NSInteger as array index Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) HTTP POST with Json on Body - Flutter/Dart Importing json file in TypeScript json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 190) Angular 5 Service to read local .json file How to import JSON File into a TypeScript file? Use Async/Await with Axios in React.js Uncaught SyntaxError: Unexpected token u in JSON at position 0 how to remove json object key and value.?

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to delimiter

How do I hide the PHP explode delimiter from submitted form results? How do I use a delimiter with Scanner.useDelimiter in Java? Split function in oracle to comma separated values with automatic sequence Split String by delimiter position using oracle SQL SQL split values to multiple rows How to use delimiter for csv in python Hive load CSV with commas in quoted fields How to escape indicator characters (i.e. : or - ) in YAML Delimiters in MySQL Split comma separated column data into additional columns