Trailing Commas in JSON
Learn why trailing commas are invalid in standard JSON, which tools tolerate them, and how to avoid this common syntax error in your JSON documents.
Detailed Explanation
A trailing comma (also called a dangling comma) is a comma placed after the last element in an array or the last key-value pair in an object. While many programming languages and data formats allow trailing commas, standard JSON strictly forbids them. This is one of the most frequent causes of JSON parse errors.
Why trailing commas are invalid:
The JSON grammar, as defined in RFC 8259 and ECMA-404, specifies that values in arrays and members in objects are separated by commas. A comma after the final element implies there is another element following, but none exists. This makes the document grammatically invalid. The specification was intentionally strict to ensure maximum interoperability across all parsers and programming languages.
The problem in practice:
Consider this object:
{
"name": "Alice",
"age": 30,
}
The comma after 30 makes this invalid JSON. Running JSON.parse() on this string throws: SyntaxError: Unexpected token } in JSON. This error message can be confusing because the actual problem is the comma, not the closing brace.
Why developers keep adding them:
In JavaScript, trailing commas are valid and even encouraged by popular style guides (Airbnb, Prettier defaults) because they produce cleaner git diffs — adding a new property does not require modifying the previous line to add a comma. Developers accustomed to writing JavaScript objects naturally add trailing commas in JSON, forgetting that JSON is a stricter format.
Common mistakes developers make:
Beyond simply adding trailing commas by habit, developers often generate JSON by concatenating strings in a loop and appending a comma after each item, including the last one. A better approach is to use JSON.stringify() or the equivalent in your language, which produces syntactically correct output. Another mistake is using a linter that auto-fixes JavaScript files but not JSON files, leaving trailing commas in place.
Tools that tolerate trailing commas:
JSONC parsers (used by VS Code and TypeScript) accept trailing commas. JSON5 also allows them. Some lenient parsers in languages like Python (json5 package) and Go (json.Decoder with custom options) can handle them. However, you should never rely on this behavior for data exchange.
Best practices:
Strip trailing commas before parsing with a strict JSON parser. Use a JSON-aware editor or linter that flags trailing commas automatically. When programmatically generating JSON, always use your language's built-in JSON serializer rather than string concatenation.
Use Case
Debugging a JSON configuration file that fails to parse after a developer copies JavaScript object syntax with trailing commas into a package.json or manifest file.