Common causes
- Calling res.json() on an empty body, such as a 204 No Content, a HEAD request or a redirect
- fetch with mode: 'no-cors', which returns an opaque response whose body is always empty
- JSON.parse('') on an empty string from localStorage, a file or a form field
- The server crashed or hit a timeout midway, sending only part of the JSON
- A missing closing } or ] in a hand-edited file
- Reading a file while another process is still writing it
How to fix it
- Inspect the raw body. In DevTools > Network check the Response tab, or log await res.text() and its length. An empty string means there is nothing to parse, not invalid JSON.
- Handle empty responses. Check res.status === 204 or an empty text before parsing, and return null or a default value. Only call res.json() when the server actually sends a body.
- Remove mode: 'no-cors'. An opaque no-cors response never exposes its body to JavaScript. Fix CORS on the server with an Access-Control-Allow-Origin header instead.
- Guard JSON.parse on stored values. Use JSON.parse(localStorage.getItem('cart') || 'null') or check for an empty string first. Wrap the parse in try/catch for user-editable data.
- Fix truncated server output. Check server logs for fatal errors, memory limits or timeouts during the request. A PHP fatal error after output has started can end the response mid-JSON.
- Close the brackets in files. For a config or data file, a validator shows where the structure ends early. Add the missing } or ] and check that the file was saved completely.
JavaScript
async function getJson(url) {
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const text = await res.text();
return text ? JSON.parse(text) : null; // empty body -> null
} How to stop it happening again
- Have APIs return a JSON body (even {}) or a 204 that the client knows not to parse
- Read the body as text first and parse only if it is non-empty
- Write files to a temporary name and rename them when complete
- Log server errors that can cut responses short