A trailing comma in JSON is a comma after the last object property or array item. {"a":1,} looks harmless if you write JavaScript every day, but it is invalid JSON. JSON.parse() expects another value after the comma and finds } or ] instead, so it throws a SyntaxError.
The fix is usually one character: remove the comma before the closing brace or bracket. The engineering decision is bigger: if the input is a hand-pasted snippet, repair it. If the input came from your API, webhook, message queue, or generator, reject it and fix the producer.
Quick Fix
| Situation | What to do |
|---|---|
| Small pasted object | Delete the comma before }. |
| Small pasted array | Delete the comma before ]. |
| Large file | Use a JSON validator to get the line/column, then remove the structural comma. |
| Repeated generated output | Stop building JSON by string concatenation; use JSON.stringify(). |
| LLM or clipboard output | Repair, then validate and review the output. |
tsconfig.json or VS Code settings |
Treat it as JSONC if the tool supports JSONC. Do not feed it to JSON.parse(). |
| API response or request body | Reject malformed JSON and fix the server/client serializer. |
| Regex cleanup script | Avoid unless you control the input and know strings cannot contain ,} or ,]. |
What a Trailing Comma Looks Like
Trailing commas appear in two structural positions.
In an object:
{
"name": "Ada",
"score": 98,
}
The comma after 98 is invalid because there is no next property.
In an array:
[
"admin",
"editor",
]
The comma after "editor" is invalid because there is no next array element.
The valid versions remove only those final commas:
{
"name": "Ada",
"score": 98
}
[
"admin",
"editor"
]
Commas between items are still required. The mistake is not "commas are bad"; the mistake is a comma with no value after it.
Why JSON Forbids Trailing Commas
In JSON, a comma is a separator, not a terminator. It separates one object member from the next object member, or one array element from the next array element.
The object rule in RFC 8259 is commonly described like this:
object = "{" [ member *( "," member ) ] "}"
member = string ":" value
The important part is "," member: a comma must be followed by another member. A final comma before } has no member after it, so the parser rejects the document.
Arrays follow the same idea. A comma inside an array must be followed by another value. A final comma before ] is invalid.
JSON made this trade-off for interoperability. A strict, small grammar is easier for different languages to parse the same way. That matters for API bodies, config shipped across tools, queues, logs, and data exports.
Why JavaScript Allows It and JSON Does Not
JavaScript object and array literals are source code. JSON is a data format. They look similar, but they are not the same grammar.
This is valid JavaScript:
const user = {
name: "Ada",
score: 98,
};
This is invalid JSON:
{
"name": "Ada",
"score": 98,
}
JavaScript allows trailing commas because they make diffs cleaner. Adding a new property often changes one line instead of touching the previous line too.
JSON does not inherit that convenience. A normal JSON parser will reject the final comma even if your editor, linter, or JavaScript runtime accepts it elsewhere.
Common Error Messages
The parser usually complains at the closing brace or bracket, not at the comma itself. That is because the parser has already accepted the comma and is waiting for another value.
| Parser | Object trailing comma | Array trailing comma |
|---|---|---|
JavaScript JSON.parse() in V8 |
Often Expected double-quoted property name or Unexpected token } |
Often Unexpected token ] |
Firefox JSON.parse() |
Often mentions expected property name or value with line/column | Often mentions expected value with line/column |
Python json.loads() |
Expecting property name enclosed in double quotes |
Expecting value |
Go encoding/json |
invalid character '}' looking for beginning of object key string |
invalid character ']' looking for beginning of value |
| jq | Parse error near object key/value | Expected another array element |
Example in JavaScript:
JSON.parse('{"name":"Ada","score":98,}');
// SyntaxError near the closing brace
JSON.parse('["admin","editor",]');
// SyntaxError near the closing bracket
When you see an error near } or ], look one character back. If that character is a comma outside a string, you found the bug.
How to Find the Trailing Comma
For a small payload, inspect the character immediately before the reported } or ].
For a larger string in JavaScript, convert the position into a preview:
function previewJsonError(text, error) {
const message = error instanceof Error ? error.message : String(error);
const match = message.match(/position (\d+)/);
if (!match) return { message };
const position = Number(match[1]);
const start = Math.max(0, position - 40);
const end = Math.min(text.length, position + 40);
return {
message,
position,
character: JSON.stringify(text[position] ?? ""),
before: JSON.stringify(text.slice(start, position)),
after: JSON.stringify(text.slice(position, end))
};
}
Run it around a strict parse:
try {
JSON.parse(raw);
} catch (error) {
console.error(previewJsonError(raw, error));
}
For files, use a parser that reports line and column:
python3 -m json.tool config.json
jq empty config.json
node -e "JSON.parse(require('node:fs').readFileSync('config.json', 'utf8'))"
python3 -m json.tool is especially handy on machines where you do not want to install anything.
Why Regex Fixes Can Break Real JSON
You will often see this quick fix:
const fixed = raw.replace(/,\s*([}\]])/g, "$1");
It removes a comma before } or ]. For small known-safe snippets, it may work. It is not a general JSON repair strategy.
The problem is strings:
{
"example": "this text contains ,} inside a string"
}
A blind regex can change string data because it does not know whether ,} is structural syntax or part of a string value. JSON escaping makes this even trickier:
{
"pattern": ",\\s*[}\\]]"
}
A proper parser or repair parser is string-aware. It can remove a structural trailing comma without touching a comma sequence inside a string.
Safer Ways to Fix a Trailing Comma
1. Remove it manually
For one small object or array, delete the comma before the closing } or ]. Then run a strict validator.
2. Regenerate the JSON
If your code produced the bad string, stop concatenating JSON manually.
Bad:
const json = `{"ids":[${ids.map((id) => `${id},`).join("")}]}`;
Good:
const json = JSON.stringify({ ids });
JSON.stringify() will not emit trailing commas.
3. Use a repair parser for human input
If the input came from a clipboard, LLM response, support ticket, or hand-edited example, a repair parser is reasonable. It can remove trailing commas and return strict JSON text.
After repair, parse again and review the result:
import { jsonrepair } from "jsonrepair";
const repaired = jsonrepair(raw);
const value = JSON.parse(repaired);
4. Use JSONC or JSON5 intentionally
If people are maintaining a config file and want comments or trailing commas, use a format that supports them and a parser that expects that format.
Use JSONC for editor and TypeScript-style config where the tool supports it. Use JSON5 when you explicitly opt into the JSON5 parser. Do not send JSONC or JSON5 over an API that says it accepts JSON.
JSON, JSONC, JSON5, and JavaScript Objects
| Format | Trailing commas? | Comments? | Common use |
|---|---|---|---|
| JSON | No | No | APIs, request bodies, response bodies, queues, strict data files |
| JSONC | Yes in supporting tools | Yes | VS Code settings, TypeScript-style config |
| JSON5 | Yes | Yes | Human-edited config when both producer and consumer opt in |
| JavaScript object literal | Yes | Yes | Source code, tests, app config written as JS/TS |
The file extension can be misleading. Some .json files are actually treated as JSONC by their tools. tsconfig.json is the familiar example. That does not mean JSON.parse() will accept the same file.
If the data crosses a language boundary, use strict JSON.
Prevent Trailing Commas in CI
For strict .json files, add a parse check to CI:
find . -name '*.json' -not -path './node_modules/*' -print0 |
xargs -0 -n1 python3 -m json.tool >/dev/null
Or check a known file:
jq empty package.json
python3 -m json.tool package.json >/dev/null
In JavaScript projects, configure formatters carefully:
{
"overrides": [
{
"files": "*.json",
"options": {
"trailingComma": "none"
}
}
]
}
Prettier generally formats JSON as strict JSON, but explicit overrides help when a repo mixes .json, .jsonc, JavaScript, and TypeScript.
For generated files, add a test that parses the output with a strict parser. The test should fail before malformed JSON ships.
LLM Output and Trailing Commas
LLMs often copy the style of JavaScript examples: unquoted keys, single quotes, comments, and trailing commas. The model may produce something that looks nice in a chat window but fails in JSON.parse().
Use this workflow:
- Ask the model for strict JSON only.
- Extract the JSON block, not the surrounding prose.
- Run a strict parse.
- If the only problem is syntax, repair and parse again.
- Validate required fields and types before using the value.
Repair is cleanup, not trust. If a model omitted a required field, invented a value, or changed a type, removing the trailing comma will not fix the data.
When to Repair vs Reject
Repair trailing commas when the input is exploratory:
- A developer pasted an object into JSON Fix.
- A support ticket contains almost-JSON.
- An LLM produced a sample with a final comma.
- A hand-written fixture needs cleanup before review.
Reject trailing commas when the input is a contract:
- API request body.
- API response body.
- Webhook payload.
- Message queue event.
- Import file for payments, permissions, migrations, or deletes.
- Generated file from your own serializer.
In those cases, a trailing comma means the producer emitted invalid JSON. Fix the producer so the next payload is correct too.
Fix It in Your Browser
If you need a quick fix, paste the sample into JSON Fix, click Repair & Format, and review the output. The tool removes structural trailing commas along with common neighbor mistakes such as single quotes, unquoted keys, comments, Python literals, undefined, markdown fences, and unclosed structures.
For important payloads:
- Validate the repaired output with JSON Validator.
- Compare before and after with JSON Diff.
- Inspect large repaired payloads in JSON Viewer.
- Keep sensitive JSON local and redact before sharing screenshots or tickets.
Frequently Asked Questions
Does JSON allow trailing commas?
No. Strict JSON does not allow a comma after the last object property or array item. A comma must separate two values; it cannot appear immediately before } or ].
Why does JSON.parse() reject { "a": 1, }?
After the comma, JSON.parse() expects another object property. Instead it finds the closing brace, so the object grammar is invalid and the parser throws a SyntaxError.
What error does a trailing comma cause?
Common messages include Unexpected token }, Unexpected token ], Expected double-quoted property name, Expecting value, or Expected another array element. The exact wording depends on the parser.
How do I remove a trailing comma from JSON?
Remove the comma before the closing } or ], then validate the result. For generated JSON, use JSON.stringify() or a serializer instead of manual string concatenation. For pasted almost-JSON, use a grammar-aware repair tool.
Can I remove trailing commas with regex?
Only for controlled inputs. A regex such as /,\\s*([}\\]])/g can corrupt string values that contain ,} or ,]. Use a parser or repair parser for untrusted or important JSON.
Why do JavaScript, JSONC, and JSON5 allow trailing commas?
They are designed for source code or human-edited config where cleaner diffs are useful. Strict JSON is a language-neutral data interchange format, so it keeps the grammar smaller and rejects final commas.
Should API clients repair trailing commas automatically?
Usually no. If an API response or request body contains a trailing comma, the producer is emitting invalid JSON. Reject it, log a safe preview, and fix the producer instead of hiding the bug downstream.
Will Prettier remove trailing commas from JSON?
For strict JSON files, Prettier should output valid JSON without trailing commas. Be careful in repos that mix JSON, JSONC, JavaScript, and TypeScript because trailing comma settings that are fine for code are not fine for strict JSON payloads.
Related Tools & Guides
- JSON Fix - repair trailing commas and other common JSON errors.
- Fix Trailing Commas in JSON - focused repair guide.
- JSON.parse Unexpected Token Errors - map token messages to causes.
- JSON vs JavaScript Objects - why JS syntax is not strict JSON.
- Fix JSON Online - how browser-based repair works.
- Repair Broken JSON in JavaScript - safe parse and repair patterns.
- JSON Formatter vs JSON Repair - choose the right tool.
- JSON Diff - compare repaired output with the original.
Sources
- RFC 8259 - JSON grammar and separators.
- ECMA-404 - the JSON data interchange syntax.
- MDN: JSON.parse() - JavaScript strict JSON parsing.
- JSON5 - JSON-adjacent syntax that allows trailing commas.
- Prettier options: trailingComma - formatter behavior for trailing commas.
Last reviewed July 2026.