Common JSON Errors and How to Fix Them
Troubleshoot the 10 most common JSON syntax errors: trailing commas, single quotes, unquoted keys, unexpected tokens, and more. Practical fixes with examples.
Try our free JSON Formatter & Validator
Paste invalid JSON and get instant error highlighting with exact line numbers.
Why JSON Errors Happen
JSON (JavaScript Object Notation) is the universal data format for web APIs, configuration files, and data exchange. Its syntax is strict by design: the RFC 8259 specification deliberately excludes features like comments, trailing commas, and single quotes that other formats allow. This strictness is what makes JSON universally parseable, but it also means a single character out of place will break everything.
Most JSON errors fall into one of three categories: syntax borrowed from JavaScript that JSON does not support (trailing commas, single quotes, comments), data type confusion (using undefined, NaN, or leading zeros), and encoding issues (BOM characters, unescaped control characters). Each section below covers specific errors with bad and good examples.
The fastest way to find and fix JSON errors is to paste your data into our JSON Formatter & Validator, which highlights the exact error position with line numbers and provides auto-fix suggestions.
Trailing Commas
Trailing commas are the number one cause of JSON parse failures. JavaScript, TypeScript, Python, and most programming languages allow trailing commas in arrays and objects, so developers naturally include them when writing JSON by hand. But the JSON specification forbids them.
1. Trailing Comma in Object
{
"name": "Alice",
"age": 30,
}{
"name": "Alice",
"age": 30
}Remove the comma after the last property. The parser expects a key-value pair after every comma, so a comma followed by a closing brace is a syntax error.
2. Trailing Comma in Array
["red", "green", "blue",]
["red", "green", "blue"]
Same rule for arrays: no comma after the last element. This is especially common when generating JSON by looping through items and appending commas.
Quote and Key Errors
JSON requires double quotes for all strings and keys. No exceptions. These errors typically come from writing JSON as if it were a JavaScript object literal.
3. Single Quotes
{'name': 'Alice'}{"name": "Alice"}JSON only allows double quotes ("). Single quotes (') are a JavaScript and Python convention. Replace all single quotes with double quotes.
4. Unquoted Keys
{name: "Alice", age: 30}{"name": "Alice", "age": 30}Every key must be a double-quoted string, even if it looks like a valid identifier. This is one of the key differences between JSON and JavaScript object literals.
5. Comments
{
// user info
"name": "Alice",
/* age */ "age": 30
}{
"name": "Alice",
"age": 30
}JSON does not support comments of any kind. Remove all // and /* */ comments. If you need comments, consider using JSONC, YAML, or TOML instead.
Need to convert your JSON data to another format? Try our JSON to YAML Converter for a format that supports comments natively.
Data Type Mistakes
JSON supports six data types: strings, numbers, booleans (true/false), null, arrays, and objects. Anything else causes a parse error.
6. undefined, NaN, and Infinity
{"value": undefined, "ratio": NaN, "max": Infinity}{"value": null, "ratio": 0, "max": 9999999}These are JavaScript-specific values that do not exist in JSON. Use null for missing values, and use a regular number as a substitute for NaN and Infinity. JSON.stringify() silently converts undefined to null and NaN/Infinity to null.
7. Leading Zeros in Numbers
{"code": 007, "zip": 01onal}{"code": 7, "zip": "01onal"}JSON numbers cannot have leading zeros (except for 0 itself and decimals like 0.5). If you need to preserve leading zeros (like ZIP codes or ID codes), use a string instead of a number.
8. Duplicate Keys
{"name": "Alice", "name": "Bob"}{"name": "Bob"}While RFC 8259 says keys SHOULD be unique, most parsers accept duplicate keys but only keep the last value. This leads to silent data loss and bugs that are extremely hard to track down. Always use unique keys.
Working with tabular JSON data? Our JSON to CSV Converter can flatten nested objects and export clean spreadsheet data.
Encoding and Character Issues
These errors are the hardest to spot because the problematic characters are often invisible or look correct in a text editor.
9. Unescaped Special Characters
{"path": "C:\Users\file.txt", "msg": "line1
line2"}{"path": "C:\\Users\\file.txt", "msg": "line1\nline2"}Backslashes and control characters must be escaped in JSON strings. A literal backslash needs \\, a literal newline needs \n, a tab needs \t. The raw characters will cause a parse error. Other characters that need escaping: \" (double quote), \/ (forward slash, optional), \b (backspace), \f (form feed), \r (carriage return).
10. BOM (Byte Order Mark) Character
\uFEFF{"name": "Alice"}{"name": "Alice"}The BOM character (U+FEFF) is an invisible character some editors add at the beginning of UTF-8 files. It causes 'Unexpected token' errors because the parser sees a non-JSON character before the opening brace. Open the file in a hex editor or use a tool to strip the BOM. In Node.js: str.replace(/^\uFEFF/, '').
Mixed encoding between UTF-8 and other character sets (like Latin-1 or Windows-1252) can also cause parsing failures. Smart quotes (“ ”) from word processors are not the same as straight double quotes (") and will break JSON. Always ensure your JSON files are saved as UTF-8 without BOM.
Debugging JSON in Code
When working with JSON programmatically, always use safe parsing patterns that handle errors gracefully instead of letting your application crash.
Safe JSON.parse() in JavaScript
function safeJsonParse(jsonString) {
try {
return { data: JSON.parse(jsonString), error: null };
} catch (err) {
return { data: null, error: err.message };
}
}
// Usage
const { data, error } = safeJsonParse(apiResponse);
if (error) {
console.error("JSON parse failed:", error);
// error message includes position:
// "Unexpected token , in JSON at position 42"
} else {
console.log("Parsed successfully:", data);
}Producing Valid JSON from JavaScript
Never build JSON by concatenating strings. Always use JSON.stringify():
// BAD: Manual string building
const bad = '{"name": "' + name + '", "age": ' + age + '}';
// GOOD: Let JSON.stringify handle escaping
const good = JSON.stringify({ name, age });
// Pretty-print with 2-space indentation
const pretty = JSON.stringify({ name, age }, null, 2);
// JSON.stringify handles special cases:
JSON.stringify({ a: undefined }); // '{}' (undefined removed)
JSON.stringify({ a: NaN }); // '{"a":null}' (NaN → null)
JSON.stringify({ a: Infinity }); // '{"a":null}' (Infinity → null)Stripping Comments and Fixing Common Issues
If you receive JSON-like data with comments or trailing commas (common with config files), you can clean it before parsing:
function cleanJsonString(str) {
return str
// Remove BOM
.replace(/^\uFEFF/, '')
// Remove single-line comments
.replace(/\/\/.*$/gm, '')
// Remove multi-line comments
.replace(/\/\*[\s\S]*?\*\//g, '')
// Remove trailing commas before } or ]
.replace(/,\s*([}\]])/g, '$1');
}
// Usage
const cleaned = cleanJsonString(dirtyJson);
const parsed = JSON.parse(cleaned);For a more robust solution, use a dedicated JSONC parser like the jsonc-parser npm package, which handles all edge cases. Or simply paste your problematic JSON into our JSON Formatter for instant error detection and auto-fix.
Frequently Asked Questions
What does 'Unexpected token' mean in JSON?
Can JSON have comments?
Why does my JSON work in JavaScript but not in a validator?
How do I find the exact line with the error?
Fix Your JSON Now
Paste invalid JSON and get instant error highlighting with exact line numbers, auto-fix suggestions, and tree view. Free, private, runs in your browser.
Open JSON Formatter & Validator