Tech Help
Why Does JSON.parse Say "Unexpected Token"?
JSON.parse throws Unexpected token when the text is not valid JSON. Debug single quotes, trailing commas, HTML responses, and error position.
JSON.parse() throws a SyntaxError when the input is not valid JSON. “Unexpected token” generally means the parser reached a character that is not allowed at that point in the structure.
Common causes include single quotes, trailing commas, unquoted property names, bad string escaping, extra text around the JSON, or parsing HTML or another non-JSON body as JSON.
The exact error wording varies by JavaScript engine and browser. Do not assume every runtime prints “Unexpected token X in JSON at position N”.
This is JSON.parse Unexpected token troubleshooting: what the error means, how to read position, and what to do when the body is HTML. Broader trailing-comma, quote, and Unexpected End coverage is in Common JSON Errors: Trailing Commas, Quotes, and Unexpected Token.
What Does “Unexpected Token” Mean in JSON.parse()?
JSON.parse() requires JSON grammar. An illegal character at the current position throws SyntaxError. {“name”:“Alex”,} is invalid: after that comma the object cannot end. Message text and position still vary by runtime.
What Error Does JSON.parse() Throw?
Invalid JSON generally throws SyntaxError. Log error.name to confirm the type. Do not hardcode the full error.message: engines and versions word it differently.
try {
JSON.parse('{"name":"Alex",}');
} catch (error) {
console.log(error.name);
// SyntaxError
}
1. Using Single Quotes Instead of Double Quotes
{‘name’:‘Alex’} is invalid JSON. {“name”:“Alex”} is valid. JSON strings and object member names use double quotes. A JavaScript object literal such as const user = { name: ‘Alex’ } can be legal JavaScript and still not be JSON text.
Invalid
{'name':'Alex'}
Valid
{"name":"Alex"}
2. Trailing Commas
A comma after the last property or array item is not valid standard JSON. {“name”:“Alex”,“age”:30,} and [1, 2, 3,] both fail. Treat this as one Unexpected token cause; Common JSON Errors: Trailing Commas, Quotes, and Unexpected Token covers trailing commas in more depth.
Invalid
{
"name": "Alex",
"age": 30,
}
Valid
{
"name": "Alex",
"age": 30
}
[1, 2, 3,]
3. Unquoted Property Names
{ name: “Alex” } can be a JavaScript object literal. In JSON, object member names are strings and need double quotes: {“name”:“Alex”}.
Invalid
{
name: "Alex"
}
Valid
{
"name": "Alex"
}
4. Invalid String Escaping
In JSON text a backslash starts an escape. A raw path like C:\Users\Alex is invalid because \U is not a legal escape. Double the backslashes. Do not mix host-language string escaping with JSON escaping. Common JSON Errors: Trailing Commas, Quotes, and Unexpected Token covers this in more depth.
Invalid
{"file":"C:\Users\Alex"}
Valid
{"file":"C:\\Users\\Alex"}
5. Extra Text Before or After the JSON
JSON.parse expects one JSON value. A prefix such as Success: before {“ok”:true}, or a suffix such as done after it, makes the whole string invalid. Insignificant whitespace around a single JSON value is allowed. JSON is not forbidden from having spaces before or after the value.
Success:
{"ok":true}
{"ok":true}
done
6. Parsing HTML Instead of JSON
Calling response.json() on an HTML page is a common Unexpected token case. Wrong endpoints, 404 or 500 HTML pages, login redirects, proxy bodies, and fallback pages often start with markup. “Unexpected token < always means HTML” is too strong: < is a clue, not proof.
fetch('/api/data')
.then(response => response.json())
What Does “Unexpected Token <” Usually Mean?
JSON values do not normally start with <. If the body begins with or , < may be the first illegal character. During local debugging, check the HTTP status, Content-Type, and the raw body. Engine wording still varies.
Check the Response Before Parsing It
The fetch body can be consumed only once. During local debugging, read text() first, inspect a short prefix, then JSON.parse that same string. Do not call response.json() and then response.text() on the same response. Do not log sensitive production payloads by default.
const response = await fetch(url);
const text = await response.text();
console.log(response.status);
console.log(response.headers.get("content-type"));
console.log(text.slice(0, 200));
try {
const data = JSON.parse(text);
console.log(data);
} catch (error) {
console.error("Invalid JSON:", error);
}
What Does “at Position 123” Mean?
Some engines report a position, line, or column. Look nearby for a bad quote, comma, brace, or escape. That index is where parsing noticed a problem; the real cause can be earlier. It is not guaranteed to be the exact faulty character.
Unexpected Token vs Unexpected End
Unexpected token means the parser met a character it did not expect. Unexpected end can appear when the input stops before the value is complete, as in {“name”:“Alex” with no closing brace. Exact wording is engine-dependent. Common JSON Errors: Trailing Commas, Quotes, and Unexpected Token covers incomplete JSON more broadly.
{"name":"Alex"
JSON Is Not the Same as a JavaScript Object Literal
JSON is a data format. A JavaScript object literal is JavaScript syntax. The JS object with unquoted keys, single quotes, and a trailing comma is not valid JSON text. JSON.parse cannot safely parse JavaScript object literals.
const data = {
name: 'Alex',
active: true,
};
{
"name": "Alex",
"active": true
}
Can JSON Contain Comments?
Standard JSON does not support comments. A // line inside an object is invalid. JSON5 and similar extensions are different formats. JSON Formatter & Diff validates standard JSON with JSON.parse and does not treat JSON5 as JSON.
{
// user name
"name": "Alex"
}
Are undefined, NaN, and Infinity Valid JSON?
No. JSON values are object, array, string, number, true, false, and null. undefined, NaN, and Infinity are not. A top-level value need not be an object or array: true, 123, “hello”, and null are valid JSON.
{"a":undefined}
{"a":NaN}
{"a":Infinity}
true
123
"hello"
null
How to Fix an Unexpected Token Error Step by Step
Work the source, not the error string:
- Confirm the input is actually JSON, not HTML, logs, or JavaScript.
- Inspect the first characters of the raw input.
- If it came from an API, check HTTP status and Content-Type. Neither 200 nor application/json guarantees valid JSON.
- Validate the syntax in a JSON parser.
- Use any reported position, line, or column as a clue, not as the guaranteed root cause.
- Check quotes, commas, braces, brackets, and escapes near that area.
- Compare with a formatted, validated copy.
- Fix the serializer or endpoint. Do not delete the reported token at random.
A global replace of ' with " can break apostrophes inside strings, already escaped text, and non-JSON sources. Produce valid JSON from the real serializer. Do not treat eval as a JSON parser.
Use JSON.stringify() When Producing JSON in JavaScript
Prefer JSON.stringify over concatenating strings by hand. It emits valid JSON text for the values it serializes. It does not preserve every JavaScript value: undefined, functions, and symbols have special behavior. That detail is out of scope here.
const data = {
name: "Alex",
active: true
};
const json = JSON.stringify(data);
// {"name":"Alex","active":true}
Invalid JSON vs a Real Fix
These pairs were checked with JSON.parse. For HTML, the fix is the response, not a syntax edit.
| Problem | Invalid | Fix |
|---|---|---|
| Single quotes | {'a':1} |
{"a":1} |
| Trailing comma | {"a":1,} |
{"a":1} |
| Unquoted key | {a:1} |
{"a":1} |
| undefined | {"a":undefined} |
{"a":null} |
| HTML body | <html>... |
Check the endpoint and raw response. Do not edit HTML into JSON. |
A Simple Unexpected Token Decision Guide
If JSON.parse failed, decide whether you even have JSON before you rewrite quotes.
- JSON.parse failed
- From an API? Check status, Content-Type, and the raw body
- Does it begin with JSON? If not, fix the source or endpoint
- If yes, validate quotes, commas, braces, brackets, escapes, unsupported values
- Use the reported position as a clue
- Fix the source, then parse again
Validate JSON Before Parsing or Using It
NEXNARA JSON Formatter & Diff validates JSON in the browser with JSON.parse—not eval.
Validate, pretty-print with 2 spaces, 4 spaces, or tabs, minify, copy, download, and upload .json. JSON Diff covers nested objects and arrays, paths, summary, filters, and swap. After parse, pretty and minified copies of the same data compare as equal; object keys are compared by name.
Text larger than 5 MB may feel slow. Text larger than 15 MB is not processed in the browser.
JSON validation and formatting happen in your browser. This tool does not send the JSON to a NEXNARA server. Ads and other site features still use the network.
Paste the failing string into JSON Formatter & Diff and read the first characters before you rewrite quotes.
FAQ
Why does JSON.parse say Unexpected token?
The text is not valid JSON at the point the parser stopped. Typical causes are quotes, commas, extra text, or a non-JSON body such as HTML.
What does Unexpected token < in JSON mean?
The first illegal character may be <. That often points to an HTML page, but it is not proof of a 404 or of HTML in every case. Check status, Content-Type, and the raw body.
How do I find the error position in JSON?
If the engine reports a position, line, or column, look near it. The real mistake can be earlier. Use it as a clue, then validate.
Can JSON use single quotes?
No. Standard JSON strings and member names use double quotes.
Can JSON have trailing commas?
No. Standard JSON does not allow a comma after the last property or array item.
How do I check if a string is valid JSON?
Call JSON.parse in a try/catch, or paste the text into JSON Formatter & Diff. If parsing throws SyntaxError, the string is not valid JSON.