Unexpected end of JSON input: why the JSON ends early
The error means parsing reached the end of the text while the JSON was not finished. Most often the response is simply empty; less often it was cut on the way.
What the error means
JSON.parse read to the end of the string and the value is still open: the string is empty, or a closing bracket or quote is missing. Chrome and Node.js say “Unexpected end of JSON input”; Firefox says “JSON.parse: unexpected end of data”. A validator shows at which character the text ends.
An empty response and response.json()
The most common cause is calling response.json() on a response with no body: 204 No Content, 201 with no data, a 500 with an empty body or a reply to HEAD. Read the text first and check the status, and parse JSON only when the text is not empty.
const res = await fetch('/api/orders/1042');
const text = await res.text(); // read text first, not res.json()
if (!res.ok) throw new Error(res.status + ': ' + text);
const data = text ? JSON.parse(text) : null; // an empty body is not a JSON errorIf the JSON is cut
A response ends early when a proxy closes the connection on a timeout, a size limit kicks in or the service crashes. Another source is copying from logs: many systems truncate long lines. Compare the real body length with the Content-Length header and look at how the response ends.
curl -s -D - https://api.example.com/orders -o body.json
wc -c body.jsonHow not to miss it in tests
Check the status code and that the body is not empty before checking field values. The report then says “204 with no body” instead of a vague parse error. In Checkcraft these are separate rules on the status and on the presence of fields.
Repeat this on your own API
Checkcraft is a desktop app that saves API response checks without code and shows what did not match. Start with a sample, then use your own sanitized data. Free runs on Windows and Linux with no time limit.
Download FreeDownload and first runNo sign-up or email needed, the archive is ready in a couple of minutes. See the edition limits.
References
Start with the linked example and compare its result with your own test requirement.