How to Fix Common JSON Syntax Errors: Unexpected Tokens & Commas
Few runtime errors are as frustrating as SyntaxError: Unexpected token in JSON at position X. You make an API call, receive a response payload, pass it into JSON.parse(), and your entire application crashes. Because JSON parsers are designed to be strictly zero-tolerance state machines, a single errant comma, an unescaped double quote, or an unexpected HTML tag will instantly halt compilation.
When a parser fails, it evaluates your byte stream character by character. The moment a byte violates the strict grammar defined in RFC 8259, it terminates and outputs the character index where the failure occurred. Understanding these common errors will help you diagnose and fix broken JSON payloads in seconds.
1. Error 1: Unexpected token < in JSON at position 0
This is by far the most commonly encountered JSON error in full-stack web development. Yet, in 99% of cases, it is not a JSON syntax mistake at all.
Notice the character the parser choked on: < at position 0 (the very first character of the payload). What format begins with the angle bracket <?
<!DOCTYPE html> or <html><head>...
The Cause: Your client requested a JSON endpoint, but the server responded with an HTML error page (such as a 404 Not Found, 500 Internal Server Error, or a 403 Forbidden Cloudflare challenge page). When your code runs response.json() or JSON.parse(data) on that HTML response, the parser fails on the first opening tag.
The Fix:
- Inspect your network tab in browser developer tools (F12) to verify the actual HTTP status code.
- Check the
Content-Typeheader returned by the server. If it saystext/htmlinstead ofapplication/json, your request failed upstream. - Always check
response.okbefore parsing responses in JavaScript:
if (!res.ok) {
const errorHtml = await res.text();
throw new Error(`Server returned status ${res.status}: ${errorHtml}`);
}
const data = await res.json();
2. Error 2: The Trailing Comma (Unexpected token } or ])
Modern languages like JavaScript (ES2017+), Python, and Dart encourage trailing commas at the end of lists and object dictionaries to make Git diffs cleaner. However, JSON explicitly forbids trailing commas.
When a parser encounters a comma after the final property, it expects another key-value pair. When it instead encounters the closing bracket (} or ]), it throws a syntax exception.
{
"id": 101,
"title": "Web Utilities",
"active": true,
}
✔ Valid JSON:
{
"id": 101,
"title": "Web Utilities",
"active": true
}
To detect and strip trailing commas across nested objects automatically, paste your payload into the Urban Mixo JSON Formatter & Validator.
3. Error 3: Single Quotes & Unquoted Keys
In standard JavaScript or Python dictionaries, single quotes are common. In JSON, **single quotes do not exist**. RFC 8259 mandates that all property names and string values must be enclosed in ASCII double quotation marks (").
{ 'status': 'complete', user: 'alex' }
✔ Valid JSON:
{ "status": "complete", "user": "alex" }
4. Error 4: Unescaped Quotes and Raw Line Breaks
If your string contains a quotation mark inside the text, or if a user input contains a raw carriage return, standard JSON parsers will terminate unexpectedly:
- Unescaped Inner Quotes: A string like
{"quote": "He said "hello""}fails because the parser interprets the second quote as the end of the string. You must escape it with a backslash:{"quote": "He said \"hello\""}. - Raw Line Breaks: Literal Enter/Return keybreaks inside a JSON string value are illegal. They must be encoded as an escaped newline token:
\n. - Binary Payloads: If your JSON payload must transport raw binary files, images, or serialized buffers, encode them to text first using a Base64 Converter before assigning them to a JSON string property.
5. Error 5: Comments in JSON (Unexpected token /)
When configuration files are formatted as JSON, developers often attempt to leave comments using // Single line or /* Block comment */.
Standard JSON has no comment specification. If you feed comments into a strict parser, it will throw: Unexpected token / in JSON at position X. If you must annotate data, consider using dedicated key conventions:
"//_comment": "This describes the following configuration option",
"timeoutSeconds": 30
}
6. How to Locate "Position X" in Massive Payloads
When error messages state Unexpected token at position 18452, finding character index 18,452 manually in a minified, single-line file is practically impossible.
- Do not paste production API keys into insecure online formatters: Many legacy tools send your input to remote servers.
- Use a secure client-side validator: Open the Urban Mixo JSON Formatter. Because it runs locally inside your browser's memory, your data is never dispatched across the network.
- Format with 2 Spaces: Formatting converts the single-line string into structured lines, instantly isolating the exact line and character column causing the break.
- Compress for Production: Once validated, compress the payload back down to its smallest transfer footprint using our JSON Minifier.
Frequently Asked Questions
Why does JavaScript allow trailing commas in objects but JSON does not?
JavaScript is a full programming language designed for development ergonomics, whereas JSON is a strict data-interchange specification. Douglas Crockford intentionally restricted JSON's grammar to make parsers fast, portable, and mathematically unambiguous across all programming languages.
How do I handle JSON with comments (JSONC)?
If your framework uses JSON with comments (such as tsconfig.json in TypeScript), standard JSON.parse() will fail. You must use a specialized parser library (such as jsonc-parser) or strip comments via regex before passing the string to a standard parser.
Can a valid JSON file start with an array?
Yes. Under RFC 8259, any valid JSON data type can serve as the root element. A file containing simply ["apple", "banana"] or even just the literal number 42 is legally valid JSON.