Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 739
Ben Combee Avatar asked Oct 14 '08 16:10

Ben Combee


People also ask

How do you escape a comma in JSON?

Hold an int (without commas) and then format the output of this int to include commas, when you output it.

Are trailing commas good practice?

In general, you should make use of trailing commas when you frequently copy/paste properties or add new items to the end of a list. You can also take advantage of them to produce cleaner diff outputs.

Is whitespace allowed in JSON?

JSON Simple Array ExamplesWhitespace (Space, Horizontal tab, Line feed or New line or Carriage return) does not matter in JSON. It can also be minified with no affect to the data. Object literal names MUST be lowercase (ie – null, false, true etc).

What is the rule for JSON syntax rules?

JSON Syntax Rules:A JSON object is surrounded by curly braces {} . The name-value pairs are grouped by a colon (:) and separated by a comma (,) . An array begins with a left bracket and ends with a right bracket [] .


2 Answers

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.

like image 125
brianb Avatar answered Oct 26 '22 18:10

brianb


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.

like image 42
Ben Combee Avatar answered Oct 26 '22 20:10

Ben Combee