You call response.json(), the promise rejects, and the console says something like SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON. The code that threw the error is almost never the code that caused it. JSON.parse is just the first thing to notice that the response isn't JSON at all.
This guide covers what each version of the "unexpected token in JSON" error is actually telling you, how to find the real cause in a couple of minutes, and how to stop it from coming back.
Reading the Error Message: The Token Is the Clue
The character after "Unexpected token" is the first character the parser choked on. That single character usually identifies the problem before you open any other file.
<at position 0: the server sent HTML. Typically a 404 page, a login redirect, a 500 error page, or your dev server's fallbackindex.html.uat position 0: you passedundefinedtoJSON.parse(). It was converted to the string "undefined", and the parser stopped at the "u".oat position 1: you passed an object that was already parsed. It became the string "[object Object]", and the parser accepted the "[" before failing on the "o".- An invisible character at position 0: almost always a byte order mark (BOM) saved at the start of a file or emitted by a PHP include.
'(single quote): the data uses single-quoted strings, which are valid in JavaScript but not in JSON.}or]somewhere in the middle: a trailing comma just before a closing bracket.
Browsers word the message differently. Recent Chrome and Node versions print the text that failed ("undefined" is not valid JSON), older V8 builds print Unexpected token < in JSON at position 0, Firefox says JSON.parse: unexpected character at line 1 column 1 of the JSON data, and Safari reports JSON Parse error: Unrecognized token '<'. They all describe the same failure.
One related message doesn't mention a token at all: "Unexpected end of JSON input". That means the string was empty or cut off. The usual cause is calling .json() on a 204 No Content response, or on a request that returned nothing because it failed.
Step 1: Look at What You Actually Received
Calling response.json() hides the raw body from you. Swap it for response.text() for a minute and log what came back:
const res = await fetch('/api/orders');
const raw = await res.text();
console.log(res.status, res.headers.get('content-type'));
console.log(raw.slice(0, 300));
const data = JSON.parse(raw);
Nine times out of ten, the log shows a status of 404, 401, or 500 with a content type of text/html, and the problem is solved before you read the JSON at all. The fix belongs on the request (wrong URL, missing auth header, a server-side bug), not in your parsing code.
You can get the same view from the terminal. curl -i prints the status line and headers above the body, so the content type and the first bytes are right there. If you don't want to assemble the flags by hand, the cURL command generator builds the request for you, including auth headers, and the beginner's guide to cURL covers the flags worth knowing.
Step 2: Match the Cause to the Fix
The server returned an HTML page
Check the status code first. A 404 means the endpoint path is wrong (a missing /api prefix, or a relative URL resolving against the current page instead of the site root). A 401 or 302 to a login page means the session or token didn't make it onto the request. A 500 means the backend crashed and the framework rendered its error page. If you're unsure what a particular code means, look it up in the HTTP status code reference.
There's also a quieter version of this problem in single-page apps. Many dev servers and hosting rewrites send index.html for any path they don't recognize, so a typo in an API URL comes back with a 200 status and a full HTML document. If the status looks fine but the body starts with <!DOCTYPE, check the URL character by character.
You parsed something twice, or parsed nothing
Unexpected token o usually comes from code like this:
const data = await res.json(); // already an object
const items = JSON.parse(data); // throws: "[object Object]" is not valid JSON
Remove the second parse. Unexpected token u is the mirror image: a variable you expected to hold a JSON string is undefined. Common sources are a misspelled property name, a function that forgot to return a value, or reading a field from an API response that doesn't include it. (A missing localStorage key behaves differently: getItem() returns null, and JSON.parse(null) quietly returns null instead of throwing.)
The JSON is almost valid
Hand-written config files and data copied from JavaScript source often contain things JSON doesn't allow:
- Single quotes around strings or keys
- Unquoted keys, such as
{name: "Jon"} - Trailing commas after the last item in an object or array
- Comments (
//or/* */) - Values like
undefined,NaN, orInfinity - A literal line break inside a string, which some engines report as "Bad control character in string literal"
Paste the text into the JSON Formatter. It validates as it formats and points to the line and column where parsing stopped, which is far quicker than counting characters to find "position 1847". Our earlier post on formatting and validating JSON online covers the validator's output in more detail.
If a file needs comments and trailing commas because people edit it by hand, JSON may simply be the wrong format for it. We compared the options in YAML vs JSON.
There's a byte order mark at the start
When the error points at position 0 but the first visible character is a perfectly normal {, suspect a BOM. It's the invisible character that some Windows editors put at the start of UTF-8 files. JSON.parse rejects it. Strip it before parsing:
const clean = raw.replace(/^/, '');
const data = JSON.parse(clean);
The permanent fix is to save the source file as UTF-8 without BOM. On a PHP backend, a BOM in any included file, or a single blank line after a closing ?> tag, gets sent ahead of your JSON. Leaving the closing tag off PHP-only files prevents the second problem entirely.
The Same Error in Python and PHP
Other languages fail on the same bad input; they just describe it differently. Python's json.loads() raises json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0), which almost always means an empty or HTML response. With the requests library, print r.status_code and r.text[:300] before calling r.json().
PHP is quieter about it. json_decode() returns null on failure and doesn't throw unless you ask it to. Pass the flag so failures can't slip through:
$data = json_decode($raw, true, 512, JSON_THROW_ON_ERROR);
Preventing It in Your Own Code
A small wrapper turns a confusing syntax error into a message that says what went wrong:
async function getJSON(url, options) {
const res = await fetch(url, options);
const type = res.headers.get('content-type') || '';
if (!res.ok) {
throw new Error(`HTTP ${res.status} from ${url}`);
}
if (res.status === 204) return null;
if (!type.includes('application/json')) {
const preview = (await res.text()).slice(0, 120);
throw new Error(`Expected JSON from ${url}, got ${type}: ${preview}`);
}
return res.json();
}
On the server side, send Content-Type: application/json with every API response, including errors. If your API returns JSON for success and an HTML page for failure, every client has to guess. The MIME types guide explains why the header matters, and the HTTP headers explainer covers the rest of the response metadata worth getting right.
Quick Diagnostic Checklist
- Log the status code and
Content-Typeheader - Log the first few hundred characters of the raw body
- Body starts with
<: fix the URL, the auth, or the server error - Error mentions
uoro: look for an undefined variable or a double parse - Empty body: handle 204 responses, or find out why nothing was returned
- Body looks like JSON: run it through a validator to find the bad character
Once you get used to reading the token as a clue, most of these errors take less time to fix than to read about.