How to Fix "Unexpected End of JSON Input"
The dreaded "Unexpected end of JSON input" error â also seen as "Unexpected end of data" or "JSON.parse: unexpected end of data" â is one of the most common JSON parsing errors developers face. It appears when a JSON parser reaches the end of the input before the JSON document is structurally complete. This guide covers every possible cause with detailed code examples and solutions.
What Does This Error Actually Mean?
The JSON parser reads your input character by character, expecting to find valid JSON tokens. When it reaches the end of the string but the JSON structure is incomplete (e.g., an object or array was opened but never closed), it throws this error. The error message typically looks like:
- JavaScript:
SyntaxError: Unexpected end of JSON input - Python:
json.JSONDecodeError: Expecting value: line 1 column 1 (char 0)(for empty input) orExpecting ',' delimiter: line X column Y - Java (Jackson):
com.fasterxml.jackson.core.JsonParseException: Unexpected end-of-input - Go:
unexpected end of JSON input - C# (Newtonsoft):
JsonReaderException: Unexpected end of content while loading JObject
All Possible Causes (With Examples)
1. Truncated JSON String
The most common cause. The JSON data was cut off during transmission, file reading, or storage.
// Original complete JSON
{"name": "John", "age": 30, "address": {"city": "NYC"}}
// Truncated â missing closing braces
{"name": "John", "age": 30, "address": {"city": "NYC"}
// Truncated â missing entire second half
{"name": "John"
How to detect: Log the raw JSON string before parsing. Compare its length to what you expect. Our JSON Validator will tell you exactly where the input ends.
2. Empty Response Body
API returns an empty string ("") or null instead of valid JSON.
// JavaScript — empty string parse
JSON.parse(""); // SyntaxError: Unexpected end of JSON input
JSON.parse(null); // SyntaxError: Unexpected end of JSON input
// Fix: check before parsing
if (response) {
try {
const data = JSON.parse(response);
} catch (e) {
console.error("Invalid JSON response:", response);
}
} else {
console.error("Empty response received");
}
Why it happens: 404 errors, 500 errors, network timeouts, or endpoints that return empty bodies. Always check HTTP status codes before parsing.
3. Missing Closing Braces or Brackets
One or more } or ] are missing at the end of the document.
// Missing one closing brace
{
"users": [
{"name": "Alice"},
{"name": "Bob"}
]
// Missing final } here!
// Missing closing bracket
{
"items": [1, 2, 3
// Missing ] and }
}
How to fix: Our JSON Repair tool can automatically add missing closing brackets. Use our JSON Depth Analyzer to visualize the structure and spot missing brackets.
4. Network Timeout or Incomplete HTTP Response
// JavaScript fetch with timeout
try {
const response = await fetch(url, { signal: AbortSignal.timeout(5000) });
const text = await response.text();
// Check response is complete
if (!text) throw new Error("Empty response");
const data = JSON.parse(text);
} catch (err) {
if (err.name === "AbortError") {
console.error("Request timed out — response may be incomplete");
} else if (err instanceof SyntaxError) {
console.error("Invalid JSON received — may be truncated");
// Log the raw response for debugging
console.log("Raw response:", text.substring(0, 1000));
}
}
5. File Read Issues
// Node.js file read
const fs = require('fs');
try {
const data = fs.readFileSync('config.json', 'utf8');
if (data.length === 0) {
throw new Error("File is empty");
}
const config = JSON.parse(data);
} catch (err) {
if (err instanceof SyntaxError) {
console.error("File contains invalid JSON. Use JSON Validator to check.");
}
}
Common causes: Partial file writes, disk full, file system corruption, or interrupted downloads.
6. Gzip'd Responses Not Decompressed
// Node.js — forgetting to decompress
const response = await fetch(url);
const buffer = await response.arrayBuffer();
// Forgot to decompress! The raw gzip bytes are not valid JSON
const text = new TextDecoder().decode(buffer);
const data = JSON.parse(text); // Unexpected end or garbage error
Fix: Use response.text() which automatically handles decompression, or decompress manually with zlib.
Step-by-Step Debugging Strategy
- Log the raw input â Always log or inspect the exact string you're passing to
JSON.parse(). Truncate it if necessary but log at least the first 500 characters. - Verify content length â Check that
Content-Lengthheaders match the actual body size. - Use our JSON Validator â Paste the raw string into our JSON Validator. It will tell you if the JSON is truncated and where.
- Check for empty responses â Before parsing, verify the string is non-empty.
- Use try/catch â Always wrap JSON.parse() in error handling.
- Check the source â Is the API endpoint correct? Is the file path correct? Is the database returning data?
- Use our JSON Repair tool â Our JSON Repair tool can fix many truncation issues automatically.
Prevention Best Practices
- Always use try/catch around every
JSON.parse()call â never assume the input is valid. - Validate with JSON Schema â Use our JSON Schema Validator to check structure and required fields.
- Set reasonable timeouts â Network requests should have timeouts to prevent hanging.
- Implement retry logic â For transient failures, retry the request.
- Monitor API health â Track error rates for endpoints serving JSON.
- Use streaming for large files â For files over 100MB, use streaming parsers instead of loading everything into memory.
- Validate before storing â Always validate JSON with our JSON Validator before writing to databases or files.