How to Fix "Unexpected token in JSON at position X"
A step-by-step diagnostic breakdown for resolving JavaScript JSON.parse() errors and malformed API payloads.
01. Unexpected token < in JSON at position 0
This is the single most common error encountered by frontend developers using fetch() or axios.
Your client code called response.json(), but the backend returned an HTML error page (starting with <!DOCTYPE html>) instead of JSON data. This happens when the endpoint returns a 404 Not Found, 500 Internal Server Error, or a reverse proxy gateway timeout (Cloudflare / Nginx error page).
// Safe fetch pattern: Check response.ok before parsing JSON
const res = await fetch('/api/user');
if (!res.ok) {
const errorHtml = await res.text();
throw new Error(`Server returned status ${res.status}: ${errorHtml.slice(0, 100)}`);
}
const data = await res.json(); 02. Trailing Commas in Objects and Arrays
In JavaScript, Python, and TypeScript, trailing commas after the final element in an array or dictionary are valid and encouraged. However, RFC 8259 strictly forbids trailing commas in standard JSON.
{
"name": "Alex",
"role": "Admin", <-- Trailing comma!
} {
"name": "Alex",
"role": "Admin"
} 03. Single-Quoted Strings and Unquoted Keys
Python str(dict), JavaScript object literal copies, and LLM completions often wrap strings in single quotes ('key': 'val') or omit quotes around keys ({key: "val"}).
Standard JSON parsers require all object property keys and string values to be wrapped in double quotes ("key": "value"). Use FormJson's Safe Repair Tool to instantly normalize them.