Home/Guides/Unexpected Token in JSON
SyntaxError Troubleshooting Guide

How to Fix "SyntaxError: Unexpected token in JSON"

Step-by-step solutions for resolving JSON syntax errors in JavaScript, Node.js, Python, and API responses. Learn why it happens and repair your payload in one click.

The "SyntaxError: Unexpected token in JSON" error occurs when a JSON parser (like JSON.parse() or res.json()) encounters a character that violates RFC 8259 JSON syntax rules, most commonly an HTML error response (like "<"), a single quote, or a trailing comma.

Diagnostic Overview

Understanding what causes unexpected token syntax errors

The "SyntaxError: Unexpected token in JSON at position X" error is one of the most frequent exceptions encountered by web developers. It occurs whenever `JSON.parse()`, `response.json()`, or a backend serialization library attempts to parse a string that violates the strict syntax rules of RFC 8259.

The "position X" in the error message represents the zero-indexed character count from the beginning of the string where the parser encountered an illegal character. For instance, position 0 means the very first character was invalid, whereas position 120 points to an issue 120 characters into your document.

Common triggers include receiving an HTML 404/500 error page from an API endpoint, using JavaScript object syntax with single quotes (`'`) or unquoted keys, leaving trailing commas after the last array item, or pasting Python dictionary string outputs containing `True` or `None`.

Understanding the exact category of your unexpected token failure allows you to prevent it in production and fix existing broken payloads instantly.

Troubleshooting Steps

Step-by-step: How to locate and fix unexpected token errors

1. Check the First Character01

Is it an HTML 404/500 page?

If the error says "Unexpected token '<' at position 0", your fetch/API call returned an HTML error page (like `<!DOCTYPE html>`) instead of JSON. Check the HTTP status code.

2. Inspect Character Position02

Locate character offset

The position number (e.g. position 42) indicates the character index where parsing broke. Look for single quotes, unquoted keys, or trailing commas.

3. Auto-Repair with JSONGlow03

One-click automated fix

Paste your broken string into JSONGlow's JSON Repair tool to automatically normalize quotes, strip comments, and prune trailing commas.

Code Demonstration

Fixing "Unexpected token '"' and Trailing Commas

Compare the malformed JavaScript/Python syntax that causes unexpected token errors with the valid JSON equivalent.

Broken Input (Causes Unexpected Token Error)
Input
{
  // Single quotes & trailing commas cause SyntaxError:
  'status': 'error',
  'code': 400,
  'messages': [
    'Invalid parameter',
  ],
}
Fixed JSON (RFC 8259 Compliant)
Processed
{
  "status": "error",
  "code": 400,
  "messages": [
    "Invalid parameter"
  ]
}
Key Difference:Replacing single quotes with double quotes, removing comments, and deleting the trailing comma after 'Invalid parameter' resolves the unexpected token SyntaxError completely.

Error Variations

The 4 most common unexpected token scenarios

!

Unexpected token '<' at position 0

Why it happens: You called `res.json()` on an API endpoint that returned an HTML error page (e.g. 404 Not Found, 502 Bad Gateway, or a Cloudflare challenge) starting with `<!DOCTYPE html>`.

Solution:Inspect `res.status` and `res.ok` before calling `res.json()`. Print `await res.text()` to inspect the raw HTML response body.
const res = await fetch('/api/data');
if (!res.ok) {
  const errorText = await res.text();
  throw new Error(`HTTP ${res.status}: ${errorText}`);
}
const data = await res.json();
!

Unexpected token ''' (single quote) at position X

Why it happens: The JSON string uses single quotes instead of standard double quotes. JSON strictly requires double quotes for all strings and object keys.

Solution:Replace single quotes with double quotes, or paste into JSONGlow JSON Repair to auto-convert all quotes.
!

Unexpected token ',' (trailing comma) at position X

Why it happens: An extra comma was left after the last element in an array `[1, 2,]` or object `{"a": 1,}`.

Solution:Delete the comma immediately preceding the closing `]` or `}`.
!

Unexpected token 'T' or 'None' (Python Literals)

Why it happens: Serializing a Python dictionary using `str(dict)` outputs `True`, `False`, or `None` instead of lowercase JSON booleans and null.

Solution:Use `json.dumps(dict)` in Python instead of `str(dict)`, or run the output through JSON Repair.

JSONGlow Developer Kit

Tools to prevent and resolve JSON syntax errors

JSON Repair Engine

Fault-tolerant parser that cleans trailing commas, normalizes single quotes, and removes comments in one click.

Line & Column Validator

Converts ambiguous character position offsets into exact line and column numbers with visual error pointers.

JSON Formatter & Beautifier

Formats clean JSON with 2-space or 4-space indentation and alphabetical key sorting for easy scanning.

JSON to TypeScript & Zod

Turn valid JSON into strongly typed TypeScript interfaces and runtime Zod validation schemas.

100% In-Browser Execution

Never risk data privacy by pasting proprietary error payloads or API secrets into remote servers.

Zero Setup & Completely Free

No account registration or paywalls. Open any tool and resolve issues immediately.

Frequently Asked Questions

Common questions answered.

Need more help? Our tools execute entirely in your browser without transmitting any payload to remote servers.

Why does JavaScript throw "SyntaxError: Unexpected token in JSON"?+

JavaScript's JSON.parse() is a strict state-machine parser based on RFC 8259. The moment it encounters a character that does not match expected grammar (e.g. a single quote, a slash for a comment, an unquoted key, or an extra comma), parsing halts immediately and throws an unexpected token SyntaxError.

How do I fix "Unexpected token '<' in JSON at position 0"?+

This error almost always means your web request received an HTML page rather than JSON. This happens when an API endpoint returns a 404 Not Found, 500 Internal Server Error, or an authentication redirect. Verify that the URL is correct, your authorization headers are present, and check `response.ok` before calling `response.json()`.

Can I automatically fix unexpected token errors online?+

Yes! Use JSONGlow's free JSON Repair tool. It parses relaxed and broken syntax, converts single quotes, removes trailing commas, strips comments, and repairs malformed structures in milliseconds without uploading your data.

How can I find the exact line and column where the token failed?+

Paste your payload into JSONGlow's JSON Validator. It will calculate the exact 1-indexed line and column number of the error and display an explanation of what token caused the failure.

Why does JSON not support trailing commas like JavaScript?+

The JSON format was finalized in 2001 by Douglas Crockford as a minimalist data interchange standard. To maximize cross-language compatibility with parsers in C, Python, Java, and C++, trailing commas were excluded from the standard grammar.

Explore More Tools

The JSONGlow developer kit.