How-To Guides

Why Trailing Commas Break JSON (With Fixes)

Trailing commas are the most common JSON syntax error. Learn why JSON forbids them, how to read the error messages, and how to fix every one.

You paste a settings block into a .json file, run your code, and JSON.parse() throws SyntaxError: Unexpected token } in JSON. You stare at the closing brace. It looks perfectly fine. The real culprit sits one character earlier: a comma after the last item in the object. That single comma is illegal in JSON, and every strict JSON parser rejects it.

This is the most common JSON syntax error developers hit, and it happens for a simple reason: JavaScript object literals happily accept trailing commas, so the habit slips into hand-written JSON. This guide explains why JSON forbids them, how to recognize the error messages they produce, and how to find and fix every one — with exact before-and-after examples you can test yourself.

Why JSON Rejects Trailing Commas

JSON looks like JavaScript, but it is a much smaller and stricter language. The JSON grammar, defined in RFC 8259, describes an object as braces wrapping zero or more name/value pairs separated by commas. The word "separated" does all the work: a comma may appear between two members, never after the last one. The same rule applies to arrays.

JavaScript object literals and arrays, by contrast, have allowed trailing commas since ES5 (as do Python, PHP, and TypeScript). They are genuinely useful in programming languages — cleaner multi-line diffs, easier line reordering — so when you copy a configuration object out of a JavaScript file into a .json file or API request body, the trailing comma comes along and the parser stops dead.

The strictness is deliberate. JSON was designed as a data interchange format that every language could parse identically with a tiny, unambiguous grammar, so the loose ends scripting languages tolerate — trailing commas, comments, single quotes, unquoted keys — were left out. Every conforming parser, from the browser's JSON.parse() to Python's json module, rejects a trailing comma.

One nuance trains the bad habit: VS Code settings files (settings.json, tsconfig.json) actually use JSONC — "JSON with Comments" — which tolerates comments and trailing commas. You write a trailing comma there, it works, and then you assume it is valid JSON. It is not: the moment that text reaches a real JSON parser, it fails.

How to Recognize a Trailing-Comma Error

Trailing-comma errors are annoying because the parser usually points at the closing bracket, not the comma. The parser reads left to right, reaches the comma, consumes it, and expects another item. When it finds } or ] instead, it reports that bracket as the "unexpected token." Train yourself to look one line above the reported position.

Here is what the error looks like in common tools:

  • Node.js / Chrome: SyntaxError: Expected double-quoted property name in JSON at position 41 (line 4 column 1) in current versions; older versions said Unexpected token } in JSON at position 41.
  • Firefox: SyntaxError: JSON.parse: expected property name or '}' at line 4 column 1 of the JSON data — the parser says it expected }, yet the comma you must delete is the one right before it.
  • Python: json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 4 column 1 (char 41).
  • Online validators: a good validator names the mistake in plain words, for example "trailing comma before the closing brace on line 3," and shows the exact line.

Because the reported position is where the parser gave up — one token past the actual mistake — the fastest diagnostic habit is simple: when the flagged line looks correct, check the end of the previous line for a stray comma.

Broken vs. Valid: Object Examples

Below is a realistic settings object of the kind you might copy out of a JavaScript file into a .json config. It contains two trailing commas: one after "push": false in the nested object, and one after the "features" line in the outer object.

Broken input:

{
  "app": "dashboard",
  "theme": "dark",
  "refreshInterval": 30,
  "notifications": {
    "email": true,
    "push": false,
  },
  "features": ["search", "export"],
}

Pasting this into JSON.parse() throws a SyntaxError pointing at the closing brace of the nested object — the first trailing comma the parser meets. Note that the parser only reports the first failure: after you fix it, it will find the second one. When a validator flags one trailing comma, always re-validate, because there are often more.

Fixed output:

{
  "app": "dashboard",
  "theme": "dark",
  "refreshInterval": 30,
  "notifications": {
    "email": true,
    "push": false
  },
  "features": ["search", "export"]
}

The fix is mechanical: delete the comma after the final member of every object. In a nested structure, that means a fix at each level — the inner object's last property and the outer object's last property are separate fixes. Watch out for one tricky variation: a trailing comma after the only property of an object.

{
  "enabled": true,
}

One property, one comma — and it is still illegal. People miss this one because a single-item object "looks" unfinished, so the comma feels natural. Delete it:

{
  "enabled": true
}

Broken vs. Valid: Array Examples

Arrays follow exactly the same rule: a comma separates elements; it may not follow the last one. The typical scenario is a list you extend while editing — you add an item, put a comma after it out of habit, and the array becomes invalid.

Broken input:

{
  "allowedColors": ["red", "green", "blue",],
  "tags": []
}

Fixed output:

{
  "allowedColors": ["red", "green", "blue"],
  "tags": []
}

Arrays of objects are where trailing commas multiply, because you can make the mistake at two levels at once:

Broken input:

[
  { "id": 1, "name": "Ada", },
  { "id": 2, "name": "Grace", },
]

Three trailing commas here — one inside each object, and one after the last object in the array. A common beginner error is to fix the array-level comma and declare victory, then get confused when the parse still fails. The rule is uniform: every comma must be between two values, at every nesting level.

Fixed output:

[
  { "id": 1, "name": "Ada" },
  { "id": 2, "name": "Grace" }
]

One more edge case: an empty array [] is valid, but [,] is not. A comma with nothing on either side is never legal.

How to Find Every Trailing Comma Quickly

For a small snippet, the fastest approach is to paste your text into the JSON Formatter & Validator and read what it reports. The tool checks your JSON as you type, names the mistake in plain words, and shows exactly where it found it. Because formatting lays each key and element on its own line, the offending comma becomes visible the moment the structure is displayed. Paste the fixed text back into your file, re-validate once more to catch any second or third comma, and you are done.

If you prefer your own editor, most code editors can find every trailing comma with one regex search — a comma followed by optional whitespace and then a closing brace or bracket:

,(\s*[\}\]])

Each match is a comma with a closing bracket right after it — exactly the illegal pattern. In VS Code you can replace all matches with $1 (the captured whitespace and bracket, without the comma) to strip them in one pass.

A word of caution about the regex approach. This pattern also matches commas inside string values. If your JSON contains a string like "note": "call me, } maybe", the regex will delete a comma that is part of the data, not a syntax error. For JSON with free-text strings, run the text through a real parser or validator after the bulk replace — or fix each match by hand. A validator understands strings; a regex does not. If a document still will not parse after your fixes, our companion guide on fixing unexpected token errors in JSON walks through the other common culprits — single quotes, unquoted keys, comments, and missing commas — with the same before-and-after treatment.

Preventing Trailing Commas in the Future

Fixing one comma is easy; never writing one again takes small changes in habit:

  • Generate JSON with code, not by hand. Build your data as a JavaScript object (trailing commas welcome there) and serialize it with JSON.stringify(). The serializer never emits a trailing comma.
  • Use a JSON-aware editor. VS Code's built-in JSON language mode underlines trailing commas in red the moment you type them in a plain .json file. Keep the file's language mode set to JSON, not JavaScript.
  • Lint before you commit. A one-line check in a build script or git hook — node -e "JSON.parse(require('fs').readFileSync('config.json','utf8'))" — catches invalid JSON before it reaches production. Python projects can use python -m json.tool config.json, which validates and pretty-prints.
  • Validate AI-generated JSON. Language models habitually produce trailing commas because they mimic JavaScript style. Always validate the output before using it.
  • Avoid hand-built JSON in loops. Assembling JSON with "..." + value + "," in a loop almost always leaves a trailing comma on the last iteration. Build an array of fragments and join(",") them, or serialize a real object.

Frequently Asked Questions

Are trailing commas ever valid in JSON?

No. RFC 8259 never allows them. Some related formats are more lenient — JSONC (VS Code settings), JSON5, and YAML allow trailing commas — but plain JSON parsed by JSON.parse(), Python's json module, or any standard API client rejects them. If a .json file accepts one, the tool reading it is being lenient, not the format.

Why does JavaScript allow trailing commas if JSON does not?

JavaScript added them to object literals and arrays to make multi-line code easier to edit — adding or reordering lines does not require touching the previous line's comma. JSON, a minimal data interchange format rather than a programming language, kept the stricter grammar so every parser in every language agrees on what is valid.

Can I remove trailing commas automatically and safely?

Yes, as long as the removal is done by something that understands JSON strings — a formatter or validator tool, or a careful editor pass where you review each match. A blind regex replace works on simple config files but can corrupt commas inside string values. Always re-validate after a bulk fix.

What if my JSON still fails after removing all trailing commas?

Then the document has a different syntax problem: single quotes instead of double quotes, unquoted property names, comments, a missing comma between items, or text that is not JSON at all (like an HTML error page from an API). Paste it into a validator that reports the exact line and error, fix that one, and repeat.

Wrapping Up

A trailing comma is a one-character mistake with an outsized ability to waste your time — mostly because the error message points at the closing bracket instead of the comma. Remember the rule: in JSON, commas go between items, never after the last one, at every level of nesting. When a parser complains, look one line above the reported position; when you fix one comma, re-validate to catch the rest; and when you generate JSON from code, let JSON.stringify() do the punctuation. Paste anything suspicious into the JSON Formatter & Validator and the answer is usually one deleted comma away.