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?
Hold an int (without commas) and then format the output of this int to include commas, when you output it.
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.
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).
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 [] .
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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With