What Causes "Unexpected End of JSON Input"?
This error occurs when JSON.parse() or another JSON parser reaches the end of the input text before the document structure is complete. The JSON is incomplete or truncated.
Common Causes:
- Unclosed bracket:
{"name": "Alice"is missing the closing}. - Truncated HTTP response: A network timeout cut the API response before it finished transmitting.
- Empty string input: Calling
JSON.parse("")orJSON.parse(null)throws this error. - Partial file read: Only part of a JSON file was read before parsing began.
- Premature stream close: A server-sent event or WebSocket stream closed mid-JSON.
// Causes of "Unexpected End of JSON Input"
JSON.parse("") // ❌ Empty string
JSON.parse('{"name"') // ❌ Truncated — missing value and closing }
JSON.parse('[1, 2, 3') // ❌ Missing closing ]
// Safe approach: always validate length and content
function safeParse(text) {
if (!text || text.trim() === '') return null;
try {
return JSON.parse(text);
} catch (e) {
console.error('JSON parse error:', e.message);
return null;
}
}
// Check response before parsing in fetch()
const res = await fetch('/api/data');
const text = await res.text();
if (text.length === 0) throw new Error('Empty response from API');
const data = JSON.parse(text);