Blog · · Updated
Trailing Comma in JSON: Why JSON.parse Fails and How to Fix It
A trailing comma makes JSON invalid. See the exact JSON.parse and Python errors, how to find and remove the comma safely, and when trailing commas are allowed.
JSON Formatter / Validator
Pretty-print, minify, and validate JSON instantly.
A trailing comma is a comma after the last item in a JSON array or object, like [1, 2,] or {"a": 1,}. Standard JSON does not allow it, so every strict parser rejects the document. The fix is to delete the comma after the last element.
If you have a file that won't parse, paste it into the JSON Formatter / Validator. It reports the line and column of the error, which usually points right at the stray comma.
Why trailing commas are invalid JSON
The JSON grammar (RFC 8259 and ECMA-404) defines an array as zero or more values separated by commas, and an object as zero or more name/value pairs separated by commas. A comma is a separator, so it must be followed by another element. A comma with nothing after it is a syntax error.
[ "red", "green", "blue", ]
The same rule applies to objects:
{
"name": "devrivet",
"version": "1.0.0",
}Both documents look fine to a human, but a strict parser stops at the comma before the closing bracket or brace.
What the error looks like
The message depends on the parser and its version, so treat the wording below as examples. These are from a current Node.js release. The position almost always points at the closing } or ] or at the comma just before it.
JSON.parse('{"a": 1,}')
// SyntaxError: Expected double-quoted property name in JSON at position 8 (line 1 column 9)
JSON.parse('[1, 2,]')
// SyntaxError: Unexpected token ']', "[1, 2,]" is not valid JSONimport json
json.loads('{"a": 1,}')
# json.decoder.JSONDecodeError: Expecting property name enclosed in double quotes: line 1 column 9 (char 8)Older JavaScript engines report a message like "Unexpected token } in JSON at position 8". If you see that form, the cause is the same. See Unexpected Token in JSON at Position: Causes and Fixes for more error messages and what they usually mean.
Tools that read JSON files often fail with their own wording. A package manager reading package.json, a CI job loading a config, or an API rejecting a request body will all fail for the same reason.
Fix it by removing the comma
Delete the comma after the last item. The rest of the file stays the same.
[ "red", "green", "blue" ]
If you generate JSON in code, avoid writing separators by hand. Build the structure and serialize it, and the serializer will place commas correctly.
const config = { name: 'devrivet', version: '1.0.0' };
const text = JSON.stringify(config, null, 2);import json
config = {"name": "devrivet", "version": "1.0.0"}
text = json.dumps(config, indent=2)Finding trailing commas in a large file
In a short file you can spot the problem by eye. In a long one, use the line and column from your parser or validator and look just before the closing bracket. Common places to find them:
# Node.js: recent versions report the line and column
node -e "JSON.parse(require('fs').readFileSync('config.json', 'utf8'))"
# Python: pretty-prints valid JSON, or reports line and column
python -m json.tool config.json
# jq: fails with a parse error on invalid JSON
jq . config.json- The last key in an object that was added by copy and paste.
- The last element of an array after an item was deleted.
- Hand-edited fixtures, seed data, and mock API responses.
- Multi-line objects where a new entry was inserted above a comma you did not notice.
You can write a regular expression to remove trailing commas automatically, but treat it as a shortcut for trusted files only:
const cleaned = text.replace(/,\s*([}\]])/g, '$1');
The problem is that this pattern also matches text inside strings. Here it silently changes a value:
const text = '{"tags": ["a, ]", "b",]}';
text.replace(/,\s*([}\]])/g, '$1');
// '{"tags": ["a]", "b"]}' <- the string "a, ]" became "a]"A safer approach walks the text once and skips anything inside double-quoted strings, removing a comma only when the next non-space character is } or ]:
function removeTrailingCommas(text) {
let out = '';
let inString = false;
for (let i = 0; i < text.length; i++) {
const ch = text[i];
if (inString) {
out += ch;
if (ch === '\\') out += text[++i]; // keep escaped chars, e.g. \"
else if (ch === '"') inString = false;
} else if (ch === '"') {
inString = true;
out += ch;
} else if (ch === ',') {
let j = i + 1;
while (/\s/.test(text[j] ?? '')) j++;
if (text[j] !== '}' && text[j] !== ']') out += ch;
} else {
out += ch;
}
}
return out;
}
JSON.parse(removeTrailingCommas('{"tags": ["a, ]", "b",]}'));
// { tags: [ 'a, ]', 'b' ] }It does not understand comments or single-quoted strings. For files that use those, parse them with a JSON5 or JSONC parser instead, and fix anything you didn't write yourself by hand.
When trailing commas are allowed
Some formats are close to JSON and accept trailing commas, and some tools that look like JSON use them by design. Know which parser you are using before you assume a file is wrong.
- JSON5 allows trailing commas, comments and unquoted keys. The json5 package for JavaScript parses them, for example JSON5.parse('{"a": 1,}').
- JSONC (JSON with Comments) is used by many editor config files and allows comments and trailing commas in many implementations. Support depends on the tool.
- tsconfig.json is parsed by the TypeScript compiler, which accepts comments and trailing commas in that file.
- VS Code settings files are parsed as JSONC, so trailing commas are accepted there.
- Standard JSON parsers such as JSON.parse, json.loads, and most APIs do not accept them.
To read a JSON5 file and write strict JSON back out, parse it with the json5 package and serialize it with JSON.stringify:
import fs from 'node:fs';
import JSON5 from 'json5';
JSON5.parse('{"a": 1,}'); // { a: 1 }
JSON5.parse('[1, 2,]'); // [ 1, 2 ]
const data = JSON5.parse(fs.readFileSync('config.json5', 'utf8'));
fs.writeFileSync('config.json', JSON.stringify(data, null, 2) + '\n');A file that works in your editor can still fail in a script or CI job. If a file has a .json extension and a tool reads it with a standard parser, remove the trailing commas even if your editor does not complain.
Pitfalls to watch for
- Empty elements are also invalid. [1,,2] and [,] fail for the same reason.
- A comma after the only element of an empty object or array is invalid too. {,} is not valid JSON.
- Single quotes, comments and unquoted keys are invalid in standard JSON, so fixing a trailing comma may not be enough.
- Minified JSON makes trailing commas harder to see. Format the text first, then check the reported position.
- Formatting does not fix every problem. A file can be pretty-printed and still contain a trailing comma.
If you paste a config with real tokens, passwords, or customer data into an online tool, check how that tool handles the text. DevRivet's JSON Formatter runs entirely in your browser, so the content is not sent to a server. Other tools may behave differently, so read their documentation before pasting anything sensitive.
FAQ
Does JSON.parse accept a trailing comma?
No. JSON.parse follows the JSON specification, so a trailing comma in an array or object throws a SyntaxError. Remove the comma before parsing.
Can I allow trailing commas in JSON.parse?
No. JSON.parse has no option for that. If you must read JSON with trailing commas, use a JSON5 or JSONC parser, or clean the text before parsing, and only for input you control.
Why does my editor accept a trailing comma in a .json file?
Many editors use a JSONC-aware mode for .json files, and some tools read those files with a parser that allows trailing commas. The file is still invalid under the strict JSON standard, and a strict parser elsewhere in your pipeline will reject it.
How do I find the trailing comma in a long file?
Use a validator that reports the line and column, such as the JSON Formatter / Validator. The error position usually points at the closing bracket or the comma just before it.
JSON Formatter / Validator
Pretty-print, minify, and validate JSON instantly.