How to Fix "Unexpected end of JSON input"
Diagnosing empty response bodies, truncated JSON payloads, and unclosed brackets in JSON.parse().
01. Why This Error Happens
The JavaScript engine throws SyntaxError: Unexpected end of JSON input when the parser reaches the end of the string while still expecting more tokens.
Calling JSON.parse("") or parsing an empty HTTP response body.
Payloads like {"items": [1, 2 missing closing ]}.
HTTP connection timed out or socket dropped before all chunks arrived.
02. Handling HTTP 204 No Content & Empty Responses
APIs frequently return HTTP 204 (No Content) or 201 for DELETE/PUT/POST requests. Always check the response status and content-length before invoking response.json():
async function fetchApi(url, options) {
const res = await fetch(url, options);
if (!res.ok) {
throw new Error(`Request failed with status ${res.status}`);
}
// Handle 204 No Content or empty responses safely
if (res.status === 204 || res.headers.get('content-length') === '0') {
return null;
}
const text = await res.text();
return text ? JSON.parse(text) : null;
} 03. Safe JSON Parse Helper for Local Storage & Configs
When reading from localStorage or reading configuration files from disk, use a defensive wrapper:
function tryParseJson(value, fallback = null) {
if (!value || typeof value !== 'string') return fallback;
try {
return JSON.parse(value);
} catch (err) {
console.warn('Malformed JSON payload, using fallback:', err.message);
return fallback;
}
}