Fix Trailing Comma in JSON: Complete Guide
Trailing commas are forbidden in JSON but valid in JS and Python. Learn why, how to find them, and how to fix them in any language or parser.
Have broken JSON right now? Fix it free in under 1 second — no signup.
Fix My JSON →A trailing comma is one of the most common JSON errors you'll encounter, and also one of the most confusing. It's valid syntax in JavaScript, allowed in Python dicts and lists, and even legal in CSS and many modern config formats. But JSON says no, absolutely not, and throws a SyntaxError the moment it finds one.
This guide covers why JSON refuses trailing commas, how to find them, and every practical way to remove them, from manual editing to automated code fixes.
What Is a Trailing Comma?
A trailing comma is a comma that appears after the last item in a list or object, with nothing following it (other than whitespace and a closing bracket).
{
"name": "Alice",
"age": 30,
}
The comma after 30 is the trailing comma. It "trails" the last element, pointing at nothing.
Same thing in arrays:
{
"tags": ["admin", "user", "editor",]
}
That comma after "editor" is also a trailing comma. Both cause an immediate parse failure.
Why JSON Rejects Trailing Commas (RFC 7159)
JSON's grammar is defined in RFC 7159 (later superseded by RFC 8259). The grammar is strict and unambiguous. An object is defined as:
object = begin-object [ member *( value-separator member ) ] end-object
Breaking this down: an object starts with {, has zero or more members, each member is separated by a comma, and ends with }. The key phrase is member *( value-separator member ): each comma must be followed by another member. A comma at the end with no following member is not part of the grammar. It's a syntax error by definition.
This strictness was intentional. Douglas Crockford designed JSON as a minimal, unambiguous data interchange format. Every ambiguity was removed. Trailing commas add ambiguity (is the next element null? missing? implied?) so they were excluded.
Compare to JavaScript: ECMAScript 5 (2009) explicitly added trailing commas to object and array literals. ES2017 extended them to function parameters. Modern JS runtimes handle them fine. But JSON predates these additions and was never updated to allow them. Compare to Python: Python allows trailing commas in tuples, lists, and dicts. In fact, a single-element tuple requires a trailing comma:(42,). Python's parser has no issue with {"name": "Alice", "age": 30,}.
The mismatch: Developers who work across JavaScript, Python, and JSON constantly switch contexts. The trailing comma habit from JS or Python bleeds into JSON, causing errors that are obvious in retrospect but easy to miss when staring at a large blob of text.
How to Find a Trailing Comma
By Eye
Look for any line that ends with a comma immediately before a } or ] on the next line (or the same line):
{
"a": 1,
"b": 2, <-- trailing comma, } follows
}
In large JSON files this is hard to spot, especially when the comma and closing bracket are separated by whitespace or blank lines.
Using Your Editor
Most JSON-aware editors flag trailing commas:
- VS Code: Install the "Error Lens" extension for inline error highlighting. The built-in JSON validator also underlines errors.
- WebStorm/IntelliJ: Built-in JSON validation highlights trailing commas with a red squiggle.
- Vim/Neovim: Use the
aleorcoc.nvimplugin with a JSON linter.
In VS Code, you can open the Problems panel (View > Problems) to see all JSON errors in the current file, including the exact line number.
Using a Linter
For automated checking in CI/CD pipelines:
# Using jsonlint (Node)
npm install -g jsonlint
jsonlint your-file.json
Using jq (Unix)
jq . your-file.json
jq outputs "parse error" with line/column info
Both tools show the exact position of the trailing comma.
How to Fix Trailing Commas Manually
If you have a small JSON file and just want to fix it quickly, open it in a text editor and search for ,\s*[}\]] using regex search. Every match is a trailing comma. Delete the comma, leaving the } or ] intact.
In VS Code:
- Press
Ctrl+H(orCmd+Hon Mac) to open Find and Replace - Enable regex mode (the
.*button) - Find:
,(\s*[}\]]) - Replace:
$1 - Click Replace All
That single find/replace removes every trailing comma in the file.
Alternatively, paste the JSON into AI JSONMedic. It detects and removes trailing commas automatically as part of its repair pipeline, along with any other issues in the same file.
Fix Trailing Commas with Code
JavaScript / Node.js
The regex approach is the most common fix. One line handles it:
function removeTrailingCommas(jsonStr) {
return jsonStr.replace(/,(\s*[}\]])/g, '$1');
}
const broken = '{"name": "Alice", "age": 30, "tags": ["admin", "user",],}';
const fixed = removeTrailingCommas(broken);
console.log(JSON.parse(fixed));
// { name: 'Alice', age: 30, tags: [ 'admin', 'user' ] }
The regex ,(\s*[}\]]) matches:
,- the trailing comma(\s*[}\]])- optional whitespace followed by}or]
The replacement $1 keeps the bracket but drops the comma.
,} as literal text. For example: {"note": "see config,}"}. The regex would incorrectly strip the comma inside the string. For production use with untrusted input, use a more robust parser:
// More robust: use a JSON5 or lenient parser
// npm install json5
const JSON5 = require('json5');
const broken = '{"name": "Alice", "age": 30,}';
const result = JSON5.parse(broken); // JSON5 allows trailing commas
console.log(result); // { name: 'Alice', age: 30 }
// Or convert back to strict JSON
const strictJson = JSON.stringify(result);
JSON5 is a superset of JSON that explicitly allows trailing commas, single quotes, comments, and other JS-friendly syntax. It's great for config files and dev tools.
Python
Python's json module is strict and rejects trailing commas. The simplest fix is a regex, same as JavaScript:
import json
import re
def remove_trailing_commas(json_str: str) -> str:
# Remove trailing commas before } or ]
return re.sub(r',(\s*[}\]])', r'\1', json_str)
broken = '{"name": "Alice", "age": 30, "tags": ["admin", "user",],}'
fixed = remove_trailing_commas(broken)
result = json.loads(fixed)
print(result)
{'name': 'Alice', 'age': 30, 'tags': ['admin', 'user']}
For a more robust solution that handles edge cases, use the demjson3 library:
# pip install demjson3
import demjson3
broken = '{"name": "Alice", "age": 30,}'
result = demjson3.decode(broken) # handles trailing commas natively
print(result)
{'name': 'Alice', 'age': 30}
Convert to strict JSON if needed
strict = demjson3.encode(result)
Node.js Script for Bulk Fixing Files
If you have a directory of JSON files with trailing commas (common in legacy projects or exported data), this script fixes them all:
const fs = require('fs');
const path = require('path');
function removeTrailingCommas(str) {
return str.replace(/,(\s*[}\]])/g, '$1');
}
function fixJsonFile(filePath) {
const original = fs.readFileSync(filePath, 'utf8');
const fixed = removeTrailingCommas(original);
// Validate before writing
try {
JSON.parse(fixed);
if (fixed !== original) {
fs.writeFileSync(filePath, fixed, 'utf8');
console.log(Fixed: ${filePath});
}
} catch (e) {
console.error(Still invalid after fix: ${filePath} - ${e.message});
}
}
function fixDirectory(dir) {
const files = fs.readdirSync(dir);
for (const file of files) {
const full = path.join(dir, file);
const stat = fs.statSync(full);
if (stat.isDirectory()) {
fixDirectory(full);
} else if (file.endsWith('.json')) {
fixJsonFile(full);
}
}
}
// Usage: node fix-trailing-commas.js ./data
fixDirectory(process.argv[2] || '.');
Run it with node fix-trailing-commas.js ./path/to/json-files and it recursively fixes every .json file in the directory.
TypeScript Version
import * as fs from 'fs';
import * as path from 'path';
function removeTrailingCommas(input: string): string {
return input.replace(/,(\s*[}\]])/g, '$1');
}
function parseWithTrailingCommaSupport<T>(jsonStr: string): T {
const cleaned = removeTrailingCommas(jsonStr);
return JSON.parse(cleaned) as T;
}
// Example usage with typed result
interface UserProfile {
name: string;
age: number;
tags: string[];
}
const raw = {"name": "Alice", "age": 30, "tags": ["admin", "user",],};
const user = parseWithTrailingCommaSupport<UserProfile>(raw);
console.log(user.name); // "Alice"
Online Tools for Fixing Trailing Commas
If you don't want to write code, several online tools fix trailing commas:
- AI JSONMedic - Paste your JSON, click Fix. Handles trailing commas plus 10 other error types in one pass. Shows a repair report of everything changed.
- JSONLint (jsonlint.com) - Validates and shows errors with line numbers, but doesn't auto-fix. You still have to edit manually.
- JSON Formatter & Validator (jsonformatter.curiousconcept.com) - Similar to JSONLint, validates but doesn't repair.
For quick one-off fixes, AI JSONMedic is the fastest option because it repairs automatically rather than just pointing out the error.
Trailing Commas in Configuration Files
One common scenario: your build tool or app uses a JSON-based config file, and you accidentally add a trailing comma. This breaks the entire tool.
package.json:{
"name": "my-app",
"version": "1.0.0",
"scripts": {
"build": "webpack",
"test": "jest",
}
}
npm and Node will throw SyntaxError: Unexpected token } in JSON when trying to read this file.
tsconfig.json are fine.
eslintrc.json, .prettierrc, etc.: These vary. Some tools use JSONC, some use strict JSON. Check the tool's documentation. As a safe default, avoid trailing commas in any .json file.
FAQ
Q: Why do trailing commas work in my JavaScript object but not in JSON.parse?They're two different things. JavaScript object literals ({ a: 1, b: 2, }) are part of the JS language spec, which has allowed trailing commas since ES5. JSON.parse implements the JSON spec (RFC 8259), which does not allow trailing commas. They look similar but follow different rules.
No. The built-in JSON.parse is spec-compliant and cannot be configured. Use a lenient parser like JSON5 (npm install json5) or a repair function before calling JSON.parse.
Add a rule to your .eslintrc: "comma-dangle": ["error", "never"] for JavaScript to prevent them, or configure your editor to use a JSON validator that flags them. For JSON files specifically, VS Code flags them automatically if the file has a .json extension.
The error message usually includes a position (e.g., Unexpected token } at position 142). Count to that character in the raw string, or use a JSON validator like jsonlint that shows the line and column. The trailing comma will be one or two characters before the reported position.
TypeScript uses strict JSON parsing for .json files (not JSONC), so trailing commas in .json files imported into TypeScript will throw a compile error. For config files (tsconfig.json, jsconfig.json), TypeScript uses JSONC and allows trailing commas.
YAML doesn't use commas as separators, so trailing commas aren't a concept in YAML. TOML also doesn't have this issue. The trailing comma problem is specific to JSON (and JSON-like formats like JSON5 and JSONC, which resolve it by allowing them).
Conclusion
Trailing commas in JSON happen because every other language you work with allows them. JavaScript, Python, CSS, YAML, TOML, most config formats, all fine with trailing commas. JSON is the strict outlier.
The fix is simple: remove the comma before } or ]. Use the regex approach for quick code fixes, JSON5 for lenient parsing in dev tools, and AI JSONMedic for one-click repair of any JSON file. For related errors, see our guides on fixing JSON syntax errors explained and common JSON mistakes.
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