Photo by Ferenc Almasi on Unsplash
Why a Trailing Comma Breaks Your Package.json
Spoiler alert: It's just a regular day in the JS world.
If you work with anything that requires a nodejs server, you have to deal with the package.json file.
That includes React, Angular, Vue, or plain node backends.
One silly thing you might have noticed about the package.json file is that it will break if you put a trailing comma.
It always gets me off-guard when I am writing the scripts section and trying to spin that server up.
Here is what it looks like:
There is nothing specific about package.json here. This is how JSON works. JSON does not support trailing commas.
Why do they do that?
What even is JSON anyway?
JSON (JavaScript Object Notation) is a lightweight data interchange format. Yes, it borrowed its syntax from JavaScript.
The whole idea behind JSON is that we can exchange data in a human-readable form. The format got widespread adoption and has become the internet standard.
This shouldn't be too surprising as XML used to be the previous standard. One quick look at the comparison between the formats should tell you why.
JSON has 2 structures:
A collection of key-value pairs (which is your javascript object, python dictionary, etc)
An ordered list (your array).
Here is how the official website defines them:
An object is an unordered set of name/value pairs. An object begins with {*left brace and ends with }right brace. Each name is followed by :colon and the name/value pairs are separated by ,comma*.
An array is an ordered collection of values. An array begins with [*left bracket and ends with ]right bracket. Values are separated by ,comma*.
As you can already tell by the definition and the image. The object has to start and end with curly braces.
The standard only allows the value or a whitespace before the ending curly brace. Same with square brackets for arrays.
This means we cannot put trailing commas by a matter of definition. A comma cannot appear before the ending brackets.
In their defense, JSON was never supposed to be a configuration format. It is a data-interchange format.
The parser would stringify your objects (with or without trailing commas) down to JSON.
You and I were never supposed to write JSON ourselves.
And you don't want a data interchange format with versions. It will be a mess. But efforts are on the way.
I am happy with JSON as it is. A data interchange format with strict rules. That makes it easier to implement parsers.
The JavaScript community tends to screw up a lot. It should not have been package.json in the first place.
JSON does not support comments. Readability is not great. And commits don't look clean when you cannot provide trailing commas.
I understand the urge as there is native support for JSON in most languages. It is easier to implement.
But in the future, we ought to move our configurations to something like toml.