JSON.parse Error in JavaScript: Common Causes and Fixes
A JSON.parse error means the input string is not valid JSON. The fix is almost never in JSON.parse() itself. The fix is in the string: quotes, commas, keys, comments, escaping, or unexpected characters.
Catch the error first
Wrap parsing in try/catch so you can inspect the bad payload and error message instead of crashing the app.
try {
const data = JSON.parse(raw)
} catch (error) {
console.error('Invalid JSON:', raw)
console.error(error)
}For the full safe parsing flow, see JSON.parse in JavaScript.
Trailing commas
// Invalid
{"name":"Alice",}
// Valid
{"name":"Alice"}JavaScript object literals sometimes allow patterns that JSON does not. Trailing commas are a common example.
Single quotes instead of double quotes
// Invalid JSON
{'name':'Alice'}
// Valid JSON
{"name":"Alice"}JSON strings and object keys must use double quotes. If the source looks like a JavaScript object literal, it may need cleanup before parsing.
Unquoted keys
// Invalid
{name:"Alice"}
// Valid
{"name":"Alice"}Comments and invalid escape sequences
// Invalid JSON with comments
{
// user name
"name": "Alice"
}
// Invalid escape
{"path":"C:
ew est"}
// Valid escaped backslashes
{"path":"C:\new\test"}If you need a JSON-safe string literal, the patterns in JSON.stringify tutorial are useful.
Debug the exact broken character
When the error reports a position, log the surrounding slice of the string so you can see what is actually there.
try {
JSON.parse(raw)
} catch (error) {
const start = Math.max(0, 40)
console.log(raw.slice(start, start + 120))
}Prevent JSON.parse errors upstream
- Always generate JSON with
JSON.stringify(), not by manual string concatenation. - Validate pasted or uploaded JSON before storing it.
- Be careful when reading JSON from localStorage or query strings.
- Normalize nested payloads before logging or reusing them.
If your payload is deeply nested, parse nested JSON in JavaScript covers safer access patterns after parsing succeeds.
Find invalid JSON fast
Paste the payload into Jsonic's JSON Formatter & Validator to surface syntax errors before they hit your code.
Validate JSON