Common causes
- The response has no body: a
204 No Content, aHEADrequest, or an error response with nothing in it. - The server crashed or the connection closed part way through the response.
JSON.parsegot an empty string, for example from an empty file, an empty environment variable or a form field.- A JSON file was truncated while it was still being written.
- Brackets or braces aren't closed, so the document stops before it's complete.
Handle empty responses in fetch
async function readJson(response) {
const text = await response.text();
return text ? JSON.parse(text) : null; // empty body, such as a 204
}
const response = await fetch("/api/items/7", { method: "DELETE" });
const data = await readJson(response); // null instead of a SyntaxErrorParse stored values safely
localStorage.getItem returns null for a missing key, and JSON.parse(null) returns null, so that case is fine. An empty string, or a value written by older code, is not:
function readStored(key, fallback) {
try {
const raw = localStorage.getItem(key);
return raw ? JSON.parse(raw) : fallback;
} catch {
return fallback; // corrupted or not JSON
}
}Frequently asked questions
Which line is the error on?
This message has no position because the parser only notices the problem when it runs out of input. Paste the JSON into the validator and look for the first unclosed {, [ or string.
Can I parse a partial JSON response?
Not with JSON.parse. If the server streams data, use a format meant for it, such as newline-delimited JSON, where each line is a complete document.
Why does response.json() fail but the network tab shows data?
Check that you don't read the body twice. A body can only be read once, so call response.text() once and parse that, instead of calling both text() and json().