jsondecode.com logo

Fix: JSON.parse() Error

A JSON parse error means the string you passed to the parser was not valid JSON. This guide covers the most common root causes in JavaScript and Python, and shows you how to handle them safely in production code.

JSON.parse() in JavaScript

JSON.parse() is synchronous and throws a SyntaxError immediately on invalid input. The safest pattern is to always wrap it in a try/catch:

// Safe wrapper
function safeParseJSON(str) {
  try {
    return { ok: true, data: JSON.parse(str) };
  } catch (e) {
    return { ok: false, error: e.message };
  }
}

const result = safeParseJSON(responseText);
if (!result.ok) {
  console.error("Failed to parse JSON:", result.error);
} else {
  console.log(result.data);
}

Parsing Fetch API Responses

A very common source of parse errors is calling response.json() on an API response that returned an HTML error page. Always check response.ok first:

async function fetchData(url) {
  const response = await fetch(url);

  if (!response.ok) {
    // Server returned 4xx/5xx — body may be HTML, not JSON
    throw new Error(`HTTP ${response.status}: ${response.statusText}`);
  }

  const contentType = response.headers.get("content-type") ?? "";
  if (!contentType.includes("application/json")) {
    throw new Error("Response is not JSON: " + contentType);
  }

  return response.json(); // safe to call now
}

json.loads() in Python

Python's json.loads() raises a json.JSONDecodeError (a subclass of ValueError) on invalid input. The error message includes the line number and column position:

import json

raw = '{"name": "Alice", "age": 30,}'  # trailing comma — invalid

try:
    data = json.loads(raw)
except json.JSONDecodeError as e:
    print(f"JSON error at line {e.lineno}, col {e.colno}: {e.msg}")
    # JSON error at line 1, col 30: Expecting property name enclosed in double quotes

Common Causes at a Glance

CauseJS Error SnippetFix
Trailing commaUnexpected token }Remove the last comma
Single quotesUnexpected token 'Use double quotes
Unquoted keyUnexpected token nQuote all keys
JavaScript commentUnexpected token /Remove comments
undefined valueUnexpected token uReplace with null
NaN valueUnexpected token NReplace with null
Empty stringUnexpected end of JSONCheck why string is empty
HTML error pageUnexpected token <Check HTTP status first

Fix Your JSON Here

Paste the JSON that is failing to parse below. The formatter highlights the error line and position so you can fix it immediately.

Input JSON
Formatted Output
Formatted JSON will appear here

Frequently Asked Questions

What causes JSON.parse() to throw a SyntaxError?

JSON.parse() throws a SyntaxError whenever the input string is not valid JSON. Common causes include: trailing commas, single-quoted strings, unquoted object keys, JavaScript comments, undefined/NaN/Infinity values, and receiving an HTML error page instead of JSON from a failed API call.

How do I safely handle JSON.parse() errors in JavaScript?

Wrap the call in a try/catch block. For example: try { const data = JSON.parse(str); } catch (e) { console.error('Invalid JSON:', e.message); }. You can also write a helper that returns null on failure instead of throwing.

Why does my API return an HTML page instead of JSON?

When a server returns a 4xx or 5xx HTTP error, some servers send an HTML error page. If your client code calls JSON.parse() on that HTML, parsing will fail. Always check response.ok (in the Fetch API) or the HTTP status code before parsing the body.

What is the Python equivalent of JSON.parse()?

In Python the equivalent is json.loads(string) from the built-in json module. It raises a json.JSONDecodeError (a subclass of ValueError) when the input is not valid JSON.

How can I validate JSON before parsing it?

In production code, wrap parsing in try/catch rather than pre-validating, since parsing and validating are essentially the same cost. For development, paste the JSON into the formatter on this page to see exactly which line and character position is invalid.

If jsondecode.com saved you time, share it with your team

Free forever. No ads. No sign-up. Help other developers find it.