Skip to content

How to Fix JSON Parse Error in JavaScript

DodaTech Updated 2026-06-24 3 min read

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

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

### Why does JSON require double quotes but JavaScript allows single quotes?

JSON is a language-independent data format specified by RFC 7159. It mandates double quotes for strings and property names to keep the parser simple and language-neutral. JavaScript's object literals are more permissive. Always serialize with JSON.stringify() which handles quoting correctly.

How do I handle large JSON without blocking the main thread?

For very large JSON payloads (50 MB+), use JSON.parse() with a streaming approach via JSON.parse() on chunks, or use the stream-json library. For extreme cases, consider using JSON.parse() with a reviver function to filter out unwanted data during parsing.

What is the most common cause of JSON parse errors in production?

Truncated responses and encoding mismatches are the most common production causes. A partial response from a failed connection or a timeout produces an incomplete JSON string. Always validate that the response Content-Type is application/json and check response.ok before parsing.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro