What the Error Means

A JSON parser reads your text one character at a time. When it finds a character that is not allowed at that spot, it stops and reports an unexpected token. The character in the message is the clue: it tells you what the parser found instead of what it expected.

Error examples
SyntaxError: Unexpected token ' in JSON at position 1
SyntaxError: Unexpected token < in JSON at position 0
SyntaxError: Unexpected token } in JSON at position 42
SyntaxError: Unexpected token u in JSON at position 0
SyntaxError: Unexpected end of JSON input

Newer browsers word it a little differently, for example Unexpected token '<', "<!DOCTYPE "... is not valid JSON, but the meaning is the same.

The Same Error in Chrome, Firefox and Safari

Every browser words the error differently, so it helps to know which message belongs to which mistake. Chrome, Edge and Node.js share the same engine:

MistakeChrome, Edge, Node.jsFirefox
HTML page instead of JSONUnexpected token '<', "<!DOCTYPE "... is not valid JSONJSON.parse: unexpected character at line 1 column 1 of the JSON data
Empty or cut-off responseUnexpected end of JSON inputJSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Key without quotesExpected property name or '}' in JSON at position 1 (line 1 column 2)JSON.parse: expected property name or '}' at line 1 column 2 of the JSON data
Trailing commaExpected double-quoted property name in JSON at position 7 (line 1 column 8)JSON.parse: expected double-quoted property name at line 1 column 8 of the JSON data
Missing commaExpected ',' or '}' after property value in JSON at position 7 (line 1 column 8)JSON.parse: expected ',' or '}' after property value in object at line 1 column 8 of the JSON data
Extra text after the JSONUnexpected non-whitespace character after JSON at position 7 (line 1 column 8)JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 8 of the JSON data

Safari uses shorter messages: JSON Parse error: Unrecognized token '<' means HTML instead of JSON, and JSON Parse error: Unexpected EOF means the text is empty or cut off. Using Python? See JSONDecodeError: Expecting value, or the full list in Common JSON Errors.

Whatever the wording, the line and column point to the problem. Paste the JSON into the JSON Validator to see that spot highlighted.

Fix It Fast

Paste your JSON into the JSON Formatter. It shows the exact line and column of the problem and can repair quotes, commas, comments and Python values automatically. For badly broken files, use JSON Repair. Everything runs in your browser, so your data is never uploaded.

Unexpected token ' (single quote)

JSON only allows double quotes around keys and strings.

Wrong
{'name': 'Emily'}
Right
{"name": "Emily"}

Seeing this from an API after sending a request with curl on Windows? cmd.exe sends single quotes as part of the body, so the server gets '{...}'. See how to send JSON with curl for the fix.

Unexpected token < (HTML instead of JSON)

The text starts with <, so it is HTML, not JSON. This almost always comes from fetch or an API call: the server returned an error page, a login page or a 404 page.

JavaScript
const response = await fetch('/api/users')
console.log(response.status)          // 404? 500? 401?
const text = await response.text()
console.log(text.slice(0, 200))       // see what really came back

Check the URL, the status code and that the server sends Content-Type: application/json.

It starts with <?xml: the server sent XML

If the message reads Unexpected token '<', "<?xml vers"... is not valid JSON, the response is an XML document, not an HTML page. Some APIs (older REST and SOAP services, RSS feeds, many error pages from gateways) answer in XML unless you ask for JSON.

Ask for JSON
const response = await fetch(url, {
  headers: { Accept: 'application/json' },
})

If the API only speaks XML, read it as XML instead of calling JSON.parse:

Read XML in the browser
const text = await response.text()
const xml = new DOMParser().parseFromString(text, 'application/xml')
console.log(xml.querySelector('name')?.textContent)

Or paste the XML into XML to JSON to turn it into JSON you can work with.

Unexpected token Followed by a Word: the Server Sent a Text Error

Newer browsers show the first characters of what they received, like Unexpected token 'u', "upstream c"... is not valid JSON. When those characters are a normal English word, the server did not send JSON at all: it sent a plain-text error message, and your code tried to parse it. The first letter of the message becomes the "unexpected token":

Error you seeWhat the server actually sent
'u', "upstream c"..."upstream connect error or disconnect/reset before headers", from a proxy or load balancer (often Envoy, for example in Kubernetes or a service mesh) that could not reach your backend
'I', "Internal S"..."Internal Server Error" (HTTP 500): the backend crashed
'B', "Bad Gateway"HTTP 502: a proxy got no valid answer from the server behind it
'S', "Service Unavailable"HTTP 503: the service is down or overloaded
'N', "Not Found"HTTP 404: wrong URL or route
'F', "Forbidden"HTTP 403: missing permission, API key or login
'T', "Too Many Requests"HTTP 429: you hit a rate limit
'R', "Request En"..."Request Entity Too Large" (HTTP 413): the request body is over the server's size limit
't', "too large" (Chrome shows 'o')A short size-limit message. The request or file is bigger than the server or service allows. Chrome names the o because it first reads the t as the start of true.
'd', "denied." or 'A', "Access denied."An access-denied message (often HTTP 401 or 403) from the server, a firewall or a web application firewall that blocked the request. Check the API key, login and IP allow-list.
'f', "failed to fetch" (Chrome shows 'i')The server could not get data from another service and returned that error as plain text. This is not the browser's own TypeError: Failed to fetch, which means no response arrived at all (network or CORS) and happens before any JSON parsing.
An invisible or strange character, like '\u001f', followed by garbled textCompressed or binary data, not text. Gzip data always starts with the byte 1F. See the next section.
'<', "<html> <he"...An HTML error page, often a 502 or 504 page from nginx or a CDN

The fix is never in the JSON parsing. Check response.ok and the status code before parsing, and log the text so you can see the real error:

JavaScript
const response = await fetch(url)
const text = await response.text()

if (!response.ok) {
  throw new Error(`HTTP ${response.status}: ${text.slice(0, 200)}`)
}
const data = JSON.parse(text)

Then fix the real cause: a backend that is down, a wrong URL, a missing API key, a rate limit, or a payload that is too big.

Unexpected Token from a PHP Backend

PHP sends everything a script prints, so debug output or a warning ends up in front of the JSON. The first characters give it away:

Error you seeWhat PHP printed before the JSON
Unexpected token 's', "string(3) "...A leftover var_dump(), which prints string(3) "out"
Unexpected token 'A', "Array ("...A leftover print_r() of an array
Unexpected token '<', "<br /> <b>"...A PHP warning or notice, such as Undefined variable, printed as HTML

Remove the debug lines, keep warnings out of the response, and send only the JSON:

PHP
<?php
ini_set('display_errors', '0');   // log errors instead of printing them
header('Content-Type: application/json');

echo json_encode($data);
exit;

Also check for a blank line or spaces before <?php in any included file, and a closing ?> followed by a newline: both add text to the response. Open the API URL directly in the browser to see exactly what it returns.

Unexpected Token with Garbled Characters: Compressed or Binary Data

If the error shows symbols like �, × or empty boxes, your code is reading bytes that are not text at all. The most common cause is gzip: the response or file is compressed, but it was read as plain text. A gzip stream always starts with the bytes 1F 8B, so the first "token" is the invisible character \u001f.

  • From an API: the server compressed the body but did not send Content-Encoding: gzip, or it compressed it twice. Browsers and fetch decompress automatically only when that header is correct, so fix the server or proxy configuration.
  • From a file: you may be opening data.json.gz or a binary file by mistake. Decompress it first.
  • Encrypted or encoded data: Base64, protobuf or encrypted payloads also look like gibberish. Decode them with the right tool; for Base64, try the Base64 Decoder.
Node.js: read a gzipped JSON file
import { readFileSync } from 'node:fs'
import { gunzipSync } from 'node:zlib'

const data = JSON.parse(gunzipSync(readFileSync('data.json.gz')).toString('utf8'))

Unexpected token } or ] (trailing comma)

A comma after the last item is not allowed in JSON.

Wrong
{
  "name": "Emily",
  "city": "London",
}
Right
{
  "name": "Emily",
  "city": "London"
}

Unexpected token u (undefined)

You passed undefined to JSON.parse. It is turned into the text "undefined", and the parser chokes on the u. A typical cause is reading a missing value from localStorage or a variable that was never set.

Older browsers show Unexpected token u in JSON at position 0. Newer Chrome and Node.js show "undefined" is not valid JSONinstead. If you see 'u', "upstream c"..., it is not this problem: see the section about text errors above.

JavaScript
const saved = localStorage.getItem('settings')   // null or a string
const settings = saved ? JSON.parse(saved) : {}

Unexpected token o (object already parsed)

JSON.parse was given an object instead of a string. The object becomes "[object Object]" and the parser fails on the o. The data is already parsed, so just use it.

Unexpected token T, F or N (Python values)

True, False and None are Python, not JSON. Use true, false and null, or create the text with json.dumps() instead of str().

Unexpected Token in a MongoDB Query

A query like db.movies.find({rating{$gt:80}}) is JavaScript, not JSON, but the cause is the same kind of typo: the colon after rating is missing. The MongoDB shell (mongosh) reads queries with the Babel parser, so it reports the spot as line:column:

Error
SyntaxError: Unexpected token, expected "," (1:22)
Wrong
db.movies.find({rating{$gt:80}})
Right
db.movies.find({ rating: { $gt: 80 } })

Babel counts columns from 0, so column 22 is the 23rd character: the second {, right where the colon should be. Every field in a filter needs name: value, and operators like $gt sit inside their own braces.

Unexpected token / (comments)

Standard JSON has no comments. Remove // and /* */ lines, or read more in our JSON comments guide.

Unexpected end of JSON input

The text is empty or cut off: a missing closing } or ], an empty response body, or a file that was not fully written. Check that the server really sends a body and that every bracket is closed. Full guide: Unexpected End of JSON Input.

Use the Position Number

"At position 42" means the 43rd character (counting starts at 0). Instead of counting by hand, paste the text into the JSON Validator, which turns the position into a line and column and highlights it.

Quick Checklist

  • Double quotes around every key and string
  • No comma after the last item
  • true, false, null in lowercase
  • No comments, no undefined, no NaN
  • The response is really JSON, not an HTML page
  • Every { and [ is closed

See all other mistakes in Common JSON Errors. Backslashes and line breaks inside strings have their own guide: Bad Escaped Character in JSON.

Frequently Asked Questions

What does 'Unexpected token in JSON' mean?

The JSON parser found a character that is not allowed at that position. The character in the message, such as ' or < or }, tells you what went wrong.

Why do I get 'Unexpected token <' when I fetch JSON?

The server sent HTML instead of JSON, usually an error, login or 404 page. Check the URL and the response status, and log response.text() to see what came back.

What does 'Unexpected token u in JSON at position 0' mean?

You passed undefined to JSON.parse. Check that the value exists before parsing, for example a missing localStorage item.

How do I fix the error quickly?

Paste the JSON into our free JSON Formatter or JSON Repair tool. It shows the exact line of the error and fixes quotes, commas, comments and Python values automatically.

Related Tools