Unexpected Token in JSON: Fix <, u, ], and Position 0 Errors
| Error message (current wording) | Older wording | Cause | Fix |
|---|---|---|---|
Unexpected token '<', "<!DOCTYPE "... is not valid JSON | Unexpected token < in JSON at position 0 | Server returned an HTML page (often an error or login page) instead of JSON | Check the HTTP status and the endpoint URL before parsing |
"[object Object]" is not valid JSON | Unexpected token o in JSON at position 1 | An object was passed to JSON.parse; it is already parsed | Use the object directly, or JSON.stringify it first if you need a string |
"undefined" is not valid JSON | Unexpected token u in JSON at position 0 | The value was undefined (missing variable, empty storage key) | Guard first: if (str) JSON.parse(str) |
Unexpected token ']', "[1,2,]" is not valid JSONExpected double-quoted property name in JSON at position 7 (line 1 column 8) | Unexpected token ] in JSON / Unexpected token } in JSON | Trailing comma after the last item of an array or object | Remove the comma before the closing bracket |
Expected property name or '}' in JSON at position 1 (line 1 column 2) | Unexpected token ' in JSON at position 1 | Single-quoted strings or unquoted keys (valid JavaScript, invalid JSON) | Use double quotes around every key and string |
Unexpected end of JSON input | Unexpected end of JSON input | Empty or truncated response body | Check the body is not empty (204, aborted request) before parsing |
You called fetch(), ran .json() on the response, and the console throws SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON (older browsers and Node versions word it Unexpected token < in JSON at position 0). The character in the message tells you what the parser found. The position tells you where it gave up, which is rarely where your mistake is. This guide maps each variant to its real cause and fix.
How to Read the Error Message
Current Chrome and Node.js use two shapes. Unexpected token '[CHAR]', "[start of input]"... is not valid JSON names the character and quotes the start of the text, which is often enough to recognise HTML or [object Object]. Expected ... in JSON at position [N] (line [L] column [C]) describes what the parser wanted and where. Older versions print Unexpected token [CHAR] in JSON at position [N], where the position is the character index from the start of the string.
| Token in error | Most likely cause |
|---|---|
< at position 0 | Server returned HTML, not JSON (see below) |
} or ] | Trailing comma before this closing bracket |
' (single quote) | Used single quotes instead of double quotes |
/ at position 0–3 | Comment in JSON (// not allowed) |
u or n | undefined or unquoted value |
| A letter at position 0 | Unquoted key or non-JSON preamble in response |
Error 1: Server Returned HTML Instead of JSON
This is the most common cause of Unexpected token < at position 0. Your fetch or XMLHttpRequest called an endpoint and got an HTML page back instead of JSON. The < is the first character of <!DOCTYPE html> or of an HTML error page, so the parser fails at once.
Causes: a wrong URL (a 404 page), a server crash (a 500 error page), an auth failure (a redirect to a login page), or a CORS error (an HTML CORS rejection).
// WRONG — assumes response is always JSON
const data = await fetch('/api/users').then(r => r.json());
// RIGHT — check status and content type first
const res = await fetch('/api/users');
if (!res.ok) {
const text = await res.text();
throw new Error(`HTTP ${res.status}: ${text.slice(0, 200)}`);
}
const contentType = res.headers.get('content-type') || '';
if (!contentType.includes('application/json')) {
throw new Error(`Expected JSON, got: ${contentType}`);
}
const data = await res.json();
Behaviour is identical across V8 (Chrome, Node.js) and SpiderMonkey (Firefox). Only the error wording differs, as covered below.
When debugging this error, read the raw response text. await res.text() shows you what the server sent, not what you expected it to send.
Error 2: Trailing Comma
JSON does not allow a comma after the last item in an object or array. JavaScript does, which is why developers write trailing commas out of habit.
// BROKEN
{"name": "Maria", "role": "admin",}
["one", "two", "three",]
// FIXED
{"name": "Maria", "role": "admin"}
["one", "two", "three"]
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
The error points to the closing } or ], not to the comma. When you see it, check the character just before the closing bracket.
Error 3: Single Quotes
JSON requires double quotes for all strings, keys and values alike. Single quotes are valid JavaScript but invalid JSON. This is the usual error when you copy a JavaScript object literal into a JSON context.
// BROKEN
{'name': 'Maria', 'role': 'admin'}
// FIXED
{"name": "Maria", "role": "admin"}
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Error 4: Unquoted Keys
JavaScript object literals allow unquoted keys when they are valid identifiers. JSON requires every key to be a double-quoted string.
// BROKEN (valid JavaScript object, invalid JSON)
{name: "Maria", role: "admin"}
// FIXED
{"name": "Maria", "role": "admin"}
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Error 5: Comments
JSON has no comments: neither // line comments nor /* */ block comments. This error shows up most often in configuration files, where people want to document their settings.
// BROKEN
{
// User settings
"theme": "dark",
"language": "en" /* default */
}
// FIXED — remove comments, or use "_comment" key
{
"_comment": "User settings",
"theme": "dark",
"language": "en"
}
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
If you need comments in your config files, switch to YAML, TOML or JSONC (JSON with Comments, which VS Code supports).
Error 6: Undefined and Non-JSON Values
JSON has six types: string, number, boolean, null, object, array. undefined, NaN, Infinity, functions, and Date objects are not valid JSON values. Stringify them and then parse the result, and you get this error.
// This silently produces invalid JSON
JSON.stringify({a: undefined, b: NaN, c: Infinity});
// Result: "{}" — undefined and NaN/Infinity become nothing or null
// Safe pattern
const safe = {
value: Number.isFinite(x) ? x : null,
data: item ?? null // undefined → null
};
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Error 7: Parsing an Empty String
JSON.parse(""), JSON.parse(null), and JSON.parse(undefined) all throw this error. It happens when an API returns an empty body (such as a 204 No Content) and you try to parse it.
// Guard against empty responses
function safeParse(text) {
if (!text || !text.trim()) return null;
try {
return JSON.parse(text);
} catch (err) {
console.error('JSON parse error:', err.message, 'Input:', text.slice(0, 100));
return null;
}
}
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Error 8: BOM or Invisible Characters
A Byte Order Mark (BOM) is an invisible character () that some Windows text editors add at the start of a file. The JSON then starts with a hidden character before the {, and you get Unexpected token at position 0.
// Strip BOM before parsing const jsonString = rawString.replace(/^/, ''); const data = JSON.parse(jsonString);
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Error 9: Concatenated JSON Objects
Log files and streaming sources sometimes hold several JSON objects back to back with no separator. The line-based form is called NDJSON (Newline Delimited JSON) or JSON Lines. JSON.parse cannot handle more than one root object.
// BROKEN — two JSON objects, not valid JSON
{"id":1,"name":"Maria"}{"id":2,"name":"Carlos"}
// FIXED — parse each line separately (NDJSON)
const objects = text
.split('
')
.filter(line => line.trim())
.map(line => JSON.parse(line));
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
Swagger UI: “is not valid JSON” Trailing Comma Error
Swagger UI throws SyntaxError: is not valid JSON when your OpenAPI spec file contains trailing commas. It is a frequent source of the error because developers edit swagger.json or inline API spec strings by hand, copying from JavaScript, where trailing commas are legal.
// swagger.json — BROKEN (trailing comma after last path)
{
"paths": {
"/users": { "get": { "summary": "List users" } },
"/orders": { "get": { "summary": "List orders" } },
}
}
// FIXED — remove the comma after the last entry
{
"paths": {
"/users": { "get": { "summary": "List users" } },
"/orders": { "get": { "summary": "List orders" } }
}
}
Tested: Node.js 22.x, Python 3.12.4, Chrome 125. Output may vary on older runtimes.
The Swagger UI message does not always say which line the trailing comma is on. Paste your spec into the ToolPry JSON Formatter: auto-fix strips every trailing comma in one click and gives you a clean spec to copy back into Swagger.
If you are using Swagger UI via CDI or npm and loading the spec from a URL, the trailing comma may be in a shared config object passed to SwaggerUIBundle. Check that object definition in your JavaScript code for the same pattern.
MDN Reference: JSON.parse() and Unexpected Token Errors
The MDN documentation for JSON.parse() specifies that the method throws a SyntaxError when the string passed to it does not conform strictly to JSON syntax. The key rule MDN points out is that JSON is not a superset of JavaScript. In particular:
- Trailing commas are not allowed (valid in JavaScript ES5+, invalid in JSON)
- Single-quoted strings are not allowed (valid in JavaScript, invalid in JSON)
- Unquoted keys are not allowed (valid in JavaScript object literals, invalid in JSON)
- Comments are not allowed (
//and/* */are valid in JS, not in JSON) undefined,NaN, andInfinityare not valid JSON values
The error message text varies by JavaScript engine: V8 (Chrome/Node.js) says “Unexpected token ',', "[1,,2]" is not valid JSON” (older versions: “Unexpected token , in JSON at position N”), while Firefox says “JSON.parse: unexpected character at line N column N”. The position number is the character offset in the original string, not a line number. The ToolPry JSON Formatter normalises this and shows the exact line and column.
Debugging Strategy
When you hit this error, first log the raw string before parsing: console.log(JSON.stringify(theString)) reveals escape sequences and invisible characters. Second, paste the value into ToolPry's JSON Formatter, which highlights the exact error location in the source. Third, go to the error position and look at the character just before it. The real problem is nearly always there, not at the position itself.
In production code, wrap every JSON.parse call in try/catch. A parse error should never crash your application: catch it, log the raw input, and fall back gracefully.
Environment-Specific Error Messages
The wording varies by environment, but the meaning is the same:
Chrome/V8: SyntaxError: Unexpected token ',', "[1,,2]" is not valid JSON for a stray comma, or Expected ',' or '}' after property value in JSON at position 7 (line 1 column 8) for a missing one. Older versions print Unexpected token , in JSON at position N.
Firefox/SpiderMonkey: SyntaxError: JSON.parse: unexpected character at line 3 column 18 of the JSON data. Firefox reports line and column numbers, which are more useful than a character position.
Node.js 18+: Multi-line error output with a visual pointer to the exact character. Node.js 20+ improved these messages further, and they now show the surrounding context.
Python: json.decoder.JSONDecodeError: Expecting ',' delimiter: line 3 column 5 (char 42). Python gives both line/column and the character offset.
Java Jackson: com.fasterxml.jackson.core.JsonParseException: Unexpected character ('}' (code 125)): was expecting comma to separate Object entries. Jackson names the character it found and what it expected, the most useful message of any JSON library.
Prevention: Stop JSON Errors Before They Happen
Defensive coding stops most JSON errors before they reach your catch block. Use your language's official JSON serializer and never build JSON strings by concatenation. JSON.stringify() in JavaScript, json.dumps() in Python, and their equivalents in every other language always produce valid JSON. Concatenated JSON works until it meets a value containing a quote, backslash or newline. At that point it silently produces invalid JSON.
Add JSON Schema validation at API boundaries. Tools like Ajv (JavaScript) and Pydantic (Python) validate incoming JSON against a schema before your business logic touches it. You get clear error messages at the point of entry instead of cryptic failures deep in your code.
Validate configuration files in CI. A syntax error in a config file should fail the build, not the production deployment. Add python3 -m json.tool config.json > /dev/null as a build step. It exits with code 1 and prints the error if the JSON is invalid.
JSON Parse Error FAQ
Why does the error position point to the wrong place?
The position in a JSON parse error is where the parser gave up, not necessarily where the mistake is. A trailing comma causes the error to be reported at the closing bracket. A missing comma causes the error at the next key. A missing opening quote causes the error at the first character of the unquoted value. The actual mistake is typically one or two characters before the reported position. Always look backward from the error position to find the real issue.
How do I find a JSON error in a very large file?
Binary search works reliably: remove the second half of the file, try to parse the first half. If it parses successfully, the error is in the second half. If it fails, the error is in the first half. Repeat until you isolate the problem to a small section. For log files or generated JSON, check your generation code — a systematic error in a generator will produce the same mistake in every record, so check the first record and the last record. Paste the problematic section into ToolPry's JSON Formatter for an exact highlighted error location.
What causes JSON errors in production that do not appear in development?
The most common cause is user-generated content with special characters. A database field containing a double quote, backslash, or control character is fine in the database but causes a JSON error when you build a JSON string by concatenating the raw value without escaping it. Always use your language's JSON serializer, which handles escaping automatically. Other production-only causes include: encoding differences (UTF-8 vs Latin-1 databases), locale-specific number formatting (some locales use comma as decimal separator), and platform-specific line endings causing issues in multiline strings.
Can I auto-fix JSON errors programmatically?
For some error types, yes. The json-repair npm package and similar libraries attempt to fix common JSON errors automatically: trailing commas, single quotes, missing quotes around keys, and truncated JSON from incomplete API responses. These are useful for processing JSON from sources you do not control (scraped data, log files, user input) where you want to recover as much data as possible rather than failing completely. For APIs you control, fix the source rather than the symptoms.
See also: Why Is My JSON Invalid?, the companion guide to every JSON syntax error.