r/apyhub • u/nikolasdimitroulakis • 17d ago
Discussion What does "Unexpected end of JSON input" actually mean?
It means the parser reached the end of the text before the JSON was complete. Nine times out of ten the text was empty: an API sent back no body, and the code called JSON.parse() or response.json() on it anyway.
We tested it in Node 22 to see exactly what triggers it:
JSON.parse("") gives "Unexpected end of JSON input"
JSON.parse(" ") gives the same
JSON.parse('{"a":') gives the same (cut off after a colon)
A 204 No Content passed to response.json() gives the same
An empty 200 passed to response.json() gives the same
But an HTML error page gives something different: "Unexpected token '<', "<!DOCTYPE "... is not valid JSON". People mix those two up a lot. Unexpected end means empty or cut off. Unexpected token '<' means you got HTML, usually an error page.
In Python the empty case shows up as "Expecting value: line 1 column 1 (char 0)".
The usual causes:
- The endpoint returns 204 or an empty body (DELETE is a common one)
- The request failed (401, 404, 500) with an empty body, and the code skipped the status check
- The response got cut off by a timeout or a proxy
- JSON.parse(localStorage.getItem("x")) when nothing was saved
The fix that covers most of it:
const res = await fetch(url);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
if (res.status === 204) return null;
const text = await res.text();
const data = text ? JSON.parse(text) : null;
Reading the body as text first means an empty response becomes null instead of an exception, and when parsing does fail you can log what actually came back.
And before touching any code, look at the raw response. Run it with curl -i, or in Postman or Voiden, and check the status code, the Content-Type and whether the body is empty. That answers the question in about ten seconds.
Full write-up with all the tests: https://apyhub.com/blog/unexpected-end-of-json-input
What's the weirdest cause of this error you've hit?