JSON Trailing Comma Error: Why It Happens and How to Fix It
Trailing commas are the most common JSON syntax error from LLM output and JavaScript developers. Learn why JSON doesn't allow them, how to find them, and how to fix them automatically.
Have broken JSON right now? Fix it free in under 1 second — no signup.
Fix My JSON →If your JSON is failing to parse with an error like Unexpected token } or Expected double-quoted property name in JSON, a trailing comma is almost certainly the cause. It's the single most common JSON syntax error — and the most preventable.
This guide covers exactly what trailing commas are, why JSON doesn't allow them, where they come from in 2026 (mostly LLM output), and how to fix them automatically.
What Is a JSON Trailing Comma?
A trailing comma is a comma that appears after the last element in an object or array, with nothing following it before the closing } or ].
{
"name": "Alice",
"score": 92,
"active": true,
}
Invalid JSON (trailing comma in array):
{
"tags": ["senior", "backend", "python",]
}
Both of these are illegal JSON. The JSON specification (RFC 8259) requires that commas separate values — there is no trailing comma allowed. The comma after true in the first example and after "python" in the second example cause a parse failure in every compliant JSON parser.
The Error Messages You'll See
Different JSON parsers produce different error messages for the same trailing comma, which makes it harder to diagnose:
Python (json.loads):
json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 5 column 1 (char 82)
Node.js (JSON.parse):
SyntaxError: Expected double-quoted property name in JSON at position 67
Browsers (Chrome/Firefox DevTools):
Uncaught SyntaxError: Unexpected token } in JSON at position 67
Go (encoding/json):
invalid character '}' looking for beginning of object key string
Rust (serde_json):
Error: trailing comma at line 5 column 1
Rust's error message is the most helpful — it says "trailing comma" directly. Most others just report the position of the closing brace, not the comma itself.
Why Trailing Commas Appear in 2026
In 2022, trailing commas mostly came from developers typing JSON by hand (muscle memory from JavaScript, which allows trailing commas). In 2026, the dominant source is LLM output.
Reason 1: Models Trained on JavaScript Code
Language models like Claude, GPT-5, and Gemini are trained on massive code corpora that include billions of lines of JavaScript, TypeScript, and Python. In JavaScript, trailing commas are valid — not just tolerated, they're linted-for by many style guides:
// Valid JavaScript — ESLint often requires this
const config = {
name: "Alice",
score: 92,
active: true, // trailing comma: valid in JS
};
When a model generates JSON, it sometimes applies JavaScript syntax rules instead of JSON rules. The result is valid-looking output that fails JSON parsers.
Reason 2: LLM Token Prediction Patterns
Models generate tokens sequentially. When a model generates a property value and then predicts the next token, it often predicts , (comma) because commas are the most statistically likely token after a value in training data. If the model then predicts } or ] to close the structure — perhaps because it's approaching a token limit — the trailing comma is already emitted.
Reason 3: Multi-Property Generation Without Lookahead
Models don't "plan" how many properties they'll generate — they emit one token at a time. This means a model that has generated 4 properties and decides on the 5th token to wrap up will have already emitted the comma separator between property 4 and a hypothetical property 5, leaving a trailing comma before }.
Reason 4: Code Examples in Training Data
Many training code examples show JSON as part of a larger code block:
data = {
"name": "Alice",
"score": 92, # note: this is a Python dict, not JSON
}
Python dicts allow trailing commas. Models often conflate Python dict syntax with JSON syntax when generating structured output.
How to Fix JSON Trailing Commas
Option 1: Fix Online Automatically
Paste your JSON into aijsonmedic.com. The repair engine detects all trailing commas — in objects and arrays, at any nesting depth — and removes them without touching the rest of your data.
This handles nested trailing commas that regex approaches often miss:
{
"user": {
"name": "Alice",
"metadata": {
"score": 92,
"tags": ["senior", "backend",],
},
},
}
The repair tool catches all three trailing commas (in the array, in the nested object, and in the outer object) in one pass.
Option 2: Fix Programmatically in Python
Using thejson_repair library (recommended for LLM pipelines):
from json_repair import repair_json
import json
broken = '''
{
"name": "Alice",
"score": 92,
"active": true,
}
'''
fixed_str = repair_json(broken)
data = json.loads(fixed_str)
print(data)
# {'name': 'Alice', 'score': 92, 'active': True}
Using regex (simple cases only):
import re
import json
def remove_trailing_commas(json_str: str) -> str:
# Remove trailing commas before } or ]
# Warning: this regex breaks on commas inside string values
pattern = r',\s*([}\]])'
return re.sub(pattern, r'\1', json_str)
broken = '{"name": "Alice", "score": 92,}'
fixed = remove_trailing_commas(broken)
data = json.loads(fixed)
Caution with the regex approach: If your JSON values contain strings with ,} or ,] patterns, the regex will incorrectly modify them. Use json_repair for anything beyond simple flat objects.
Option 3: Fix Programmatically in JavaScript/TypeScript
Using thejsonrepair npm package:
import { jsonrepair } from "jsonrepair";
const broken = `{
"name": "Alice",
"score": 92,
"active": true,
}`;
const fixed = jsonrepair(broken);
const data = JSON.parse(fixed);
console.log(data);
// { name: 'Alice', score: 92, active: true }
Using regex (simple cases only):
function removeTrailingCommas(jsonStr) {
return jsonStr.replace(/,\s*([}\]])/g, '$1');
}
const broken = '{"name": "Alice", "active": true,}';
const fixed = removeTrailingCommas(broken);
const data = JSON.parse(fixed);
The same caveat applies: regex is unreliable if values contain commas followed by closing brackets.
Option 4: Use JSON5 or JSONC Parsers (Where Permitted)
If you control the parser (your own application, a config file you write), you can switch to a superset of JSON that allows trailing commas:
import JSON5 from "json5";
// JSON5 allows trailing commas
const data = JSON5.parse('{"name": "Alice", "score": 92,}');
// For tsconfig.json, VS Code settings — these use JSONC (JSON with Comments)
// JSONC allows trailing commas; the VS Code JSON parser handles them
This doesn't help when you're consuming JSON from an external API or LLM — you can't change the parser there. But for your own config files, JSON5 or JSONC eliminates the problem entirely.
Finding Trailing Commas Without a Tool
If you prefer to locate trailing commas manually before fixing them, a well-crafted regex find in your editor works:
VS Code regex find:,\s*[}\]]
This matches a comma followed by optional whitespace followed by } or ]. Press Ctrl+F, enable regex mode, and paste the pattern. Each match is a trailing comma location.
grep -n ',\s*[}\]]' yourfile.json
Preventing Trailing Commas in LLM Pipelines
The most reliable fix is upstream: structure your prompts to output JSON without trailing commas.
Prompt addition:Output valid JSON only. Do not include trailing commas. Follow RFC 8259 strictly.
Better: use structured output instead of prompting for JSON
If your LLM provider supports grammar-constrained decoding, use it. OpenAI's response_format: json_schema and Anthropic's tool use with input_schema both guarantee structurally valid JSON — including no trailing commas — at the token level:
# OpenAI — trailing commas impossible with json_schema + strict
response = client.chat.completions.create(
model="gpt-5",
response_format={
"type": "json_schema",
"json_schema": {"name": "result", "schema": schema, "strict": True}
},
messages=[...]
)
# Anthropic — trailing commas impossible via tool_choice
response = client.messages.create(
tools=tools,
tool_choice={"type": "tool", "name": "extract"},
messages=[...]
)
When you use structured output APIs, the FSM (Finite State Machine) that governs token selection physically cannot emit a trailing comma — only valid tokens for the current schema position are allowed.
Defensive catch in application code:from json_repair import repair_json
import json
def safe_parse_llm_json(raw: str) -> dict:
try:
return json.loads(raw)
except json.JSONDecodeError:
repaired = repair_json(raw)
return json.loads(repaired)
Use this wrapper in every LLM pipeline that outputs JSON. The try/repair/parse pattern costs a few milliseconds on the happy path and prevents pipeline failures on every edge case.
Trailing Commas vs Other Common JSON Errors
| Error | Cause | Fix |
|---|---|---|
| Trailing comma | Comma after last item before } or ] | Remove the trailing comma |
| Missing comma | No comma between two adjacent items | Add comma between items |
| Single quotes | 'value' instead of "value" | Replace with double quotes |
| Unquoted key | {name: "Alice"} instead of {"name": "Alice"} | Quote the key |
| Python booleans | True, False, None | Replace with true, false, null |
| Trailing garbage | Prose after closing } | Strip the text after the JSON |
All of these are handled by the aijsonmedic.com repair tool in a single pass.
FAQ
Q: Why does JavaScript allow trailing commas but JSON doesn't?JavaScript added trailing comma support in ES5 (2009) to simplify array and object manipulation — adding a new item at the end doesn't require editing the previous line. JSON was designed as a language-independent data interchange format with a strict minimal grammar. The JSON spec has never been updated to allow trailing commas, and its author (Douglas Crockford) has explicitly stated they won't be added.
Q: Will removing trailing commas ever change the meaning of my data?No. A trailing comma carries no semantic information — it's just a syntax error. Removing it restores valid JSON without modifying any key or value.
Q: Can JSONC or JSON5 solve this permanently for config files?Yes, for files you control. VS Code settings, TypeScript configs, and many developer tools support JSONC (JSON with Comments) which allows trailing commas. If you're writing the file yourself, switching to JSONC eliminates the problem. For JSON received from external sources (APIs, LLMs), you can't control the format.
Q: My JSON has nested trailing commas. Will the fix catch all of them?The aijsonmedic.com repair tool and the json_repair Python library both fix trailing commas at all nesting depths in one pass. The regex approach only reliably catches the outermost level — use a proper repair library for nested structures.
Most JSON parsers report the position where parsing failed — the } or ] — rather than the cause (the comma). The parser expected a value or property name (since there was a comma), found } instead, and threw the error at the } position. Rust's serde_json is the exception — it explicitly names "trailing comma" in the error.
Trailing commas account for approximately 31% of all JSON parsing failures in LLM pipelines according to production data from JSON repair services. Single quotes and Python boolean literals (True/False/None) together account for another 28%. These three patterns — trailing commas, single quotes, Python booleans — cause nearly 60% of all LLM JSON parse failures.
Still dealing with broken JSON?
Paste it in and get it fixed in under 1 second — free, no signup, no install. Works with ChatGPT, Claude, n8n, and any AI output.
Fix My JSON Free →Related Articles