How to Fix JSON Parse Error in JavaScript
In this tutorial, you'll learn about How to Fix JSON Parse Error in JavaScript. We cover key concepts, practical examples, and best practices.
The Problem
JSON.parse() throws a SyntaxError when the input string is not valid JSON, commonly from trailing commas, single quotes, missing quotes around property names, or truncated responses.
Quick Fix
Step 1: Validate the JSON string
Passing malformed JSON to JSON.parse() throws:
const data = JSON.parse("{ name: 'Alice' }");
SyntaxError: Unexpected token n in JSON at position 2
Property names must be double-quoted and strings must use double quotes:
const data = JSON.parse('{"name": "Alice"}');
console.log(data);
{ name: 'Alice' }
Step 2: Remove trailing commas
JSON does not allow trailing commas:
const data = JSON.parse('[1, 2, 3,]');
SyntaxError: Unexpected token ] in JSON at position 9
Remove the trailing comma:
const data = JSON.parse('[1, 2, 3]');
console.log(data);
[1, 2, 3]
Step 3: Use try/catch for parsing
Always wrap JSON.parse() in error handling:
function safeJSON(str) {
try {
return JSON.parse(str);
} catch (e) {
console.error('JSON parse failed:', e.message);
return null;
}
}
console.log(safeJSON('{"valid": true}'));
console.log(safeJSON('invalid json'));
{ valid: true }
JSON parse failed: Unexpected token i in JSON at position 0
null
Step 4: Check for truncated API responses
Network issues can truncate JSON. Always validate the response length and content:
async function fetchJSON(url) {
const res = await fetch(url);
const text = await res.text();
if (!text || text.length < 2) {
throw new Error('Empty or truncated response');
}
try {
return JSON.parse(text);
} catch (e) {
console.error('Invalid JSON response from server');
return null;
}
}
Prevention
- Always wrap
JSON.parse()in try/catch blocks. - Validate JSON before parsing using
JSON.parse()inside try/catch. - Use a schema validator like Zod or Ajv to validate parsed data.
- Never parse user-supplied strings without validation.
Common Mistakes with json parse
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro