Trailing Commas in JSON: The Ultimate Guide
One of the most frequent causes of broken API requests and crashed CI pipelines is the humble trailing comma.
While modern programming languages are very forgiving about trailing commas, the JSON specification is absolutely ruthless.
What is a Trailing Comma?
A trailing comma is a comma placed after the final element in an array or the final key-value pair in an object.
{
"name": "John Doe",
"age": 30, // <-- This is a trailing comma
}
In JavaScript (and Python, Ruby, Go, etc.), this is completely valid syntax. In fact, adding trailing commas is considered a best practice in modern JavaScript because it results in cleaner Git diffs when adding new lines.
However, in standard JSON, a trailing comma is strictly forbidden.
Why does JSON forbid trailing commas?
JSON (RFC 8259) was designed to be as simple, lightweight, and unambiguous as possible to make writing parsers easy across any programming language.
Allowing a trailing comma introduces ambiguity: does the comma mean there is a missing element, or does it signify the end of the list? By strictly forbidding it, the JSON spec ensures that every parser, whether written in C, Java, or Rust, interprets the data exactly the same way without requiring complex look-ahead logic.
How to Fix Trailing Commas
If you attempt to parse JSON with a trailing comma in Node.js or the browser, you will encounter a fatal error:
JSON.parse('{"id": 1, }')
// 💥 SyntaxError: Expected property name or '}' in JSON at position 10
1. Use a JSON Repair Tool
If you are dealing with a massive configuration file or log dump, manually finding the trailing comma is like finding a needle in a haystack.
The easiest solution is to copy the data and paste it into the JSON Nova Auto-Repair Tool. The repair engine will instantly scan the payload, strip out all illegal trailing commas, and return a clean, strictly valid JSON string.
2. Configure Your Linter
If you are writing JSON configuration files (like package.json or .eslintrc.json) in VS Code, ensure you have a linter enabled. Prettier, for example, can be configured to automatically format JSON and remove trailing commas on save.
3. Consider JSON5
If you are writing configuration files meant only for humans (and not for strict machine-to-machine API communication), you might consider using JSON5.
JSON5 is an extension of standard JSON that explicitly allows trailing commas, unquoted keys, and comments. You can convert between the two formats seamlessly using a JSON5 Formatter.
Summary
Trailing commas are great in JavaScript code, but they have no place in JSON payloads. Always validate your data using a strict JSON Validator before pushing to production to ensure a single rogue comma doesn't bring down your application.