How to Fix "Unexpected End of JSON Input" Error
Understand the Error
The "Unexpected end of JSON input" error occurs when JavaScript tries to parse JSON data that is incomplete, empty, or truncated. This commonly happens with fetch API calls, JSON.parse(), and API responses. Use our JSON validator to check your JSON structure.
Example: Code That Causes This Error
This fetch code will throw "Unexpected end of JSON input" if the API returns empty or invalid data:
fetch('/api/users') .then(response => response.json()) // ❌ Throws error if empty .then(data => console.log(data)) .catch(error => console.error(error)); // Error: "SyntaxError: Unexpected end of JSON input"
Debug Your API Response
Before parsing JSON, always check what your API is actually returning. Use the tool above to validate and fix any JSON issues:
response.text() to see raw response dataapplication/json headerCommon Causes and Solutions
1. Empty or Null Response
The API returns an empty string, null, or undefined. Always check for empty responses before calling .json().
2. Server Returns HTML Error Page
When APIs fail (404, 500), servers often return HTML error pages instead of JSON, which breaks JSON parsing.
3. Truncated JSON Response
Network interruptions or server timeouts can cut off JSON mid-transmission, leaving incomplete data.
4. CORS or Authentication Errors
CORS or auth failures may return empty responses or error pages that can't be parsed as JSON.
Implement Proper Error Handling
Add defensive checks to prevent "Unexpected end of JSON input" errors in your code:
The Correct Way to Handle JSON Parsing
Here's a robust solution that prevents "Unexpected end of JSON input" errors:
async function fetchJSON(url) {
try {
const response = await fetch(url);
// Check if request was successful
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// Check content type
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('application/json')) {
throw new Error('Response is not JSON');
}
// Get response as text first
const text = await response.text();
// Handle empty response
if (!text || text.trim().length === 0) {
console.warn('Empty response received');
return null; // or return default value
}
// Now safely parse JSON
try {
return JSON.parse(text);
} catch (parseError) {
console.error('JSON parse error:', parseError);
console.error('Response text:', text);
throw new Error('Invalid JSON in response');
}
} catch (error) {
console.error('Fetch error:', error);
throw error;
}
}
// Usage
fetchJSON('/api/users')
.then(data => {
if (data) {
console.log('Success:', data);
}
})
.catch(error => {
console.error('Failed to fetch:', error.message);
});✅ This solution: Checks response status, validates content type, handles empty responses, and provides detailed error messages for debugging—preventing the "Unexpected end of JSON input" error.
Before and After: Error Handling Comparison
See how proper error handling prevents the "Unexpected end of JSON input" error:
❌ Problematic Code (Before)
// Fragile: Breaks on empty response
fetch('/api/data')
.then(res => res.json())
.then(data => console.log(data))
.catch(err => console.error(err));
// Error:
// SyntaxError: Unexpected end
// of JSON input✅ Robust Code (After)
// Safe: Handles all edge cases
fetch('/api/data')
.then(res => {
if (!res.ok) throw Error(res.status);
return res.text();
})
.then(text => text ? JSON.parse(text) : {})
.then(data => console.log(data))
.catch(err => console.error(err));
// Success: No errors!✅ Key Difference: The improved code checks the response status, converts to text first, validates it's not empty, and only then parses as JSON—eliminating the "Unexpected end of JSON input" error entirely.
Frequently Asked Questions
What does "Unexpected end of JSON input" mean?
It's the error JSON.parse() throws when the text it gets is incomplete, empty or truncated. It shows up a lot with the fetch API when the server returns an empty body, an HTML error page, or a connection drops and cuts the JSON off mid-way.
How do I fix this error in the fetch API?
Check response.ok before you call .json(). Read response.text() first to see the raw body, confirm it isn't empty, and check the Content-Type header is application/json before parsing. If the JSON itself is broken, paste it into the tool above to have it repaired.
Why does my API return an empty response?
Usually a CORS problem, an authentication failure, a 404 or a 500. Open your browser DevTools Network tab to see the real status code and response headers — the server may be sending an HTML error page instead of JSON, which also triggers this error.
Can I prevent this error with try-catch?
A try-catch catches the error after it happens, which is a useful safety net, but it is better to prevent it: check for an empty body and a non-200 status before you parse. Doing both gives you clearer error messages and control over what happens when a request fails.
Does this error happen with axios or other libraries?
Axios parses JSON for you and has friendlier defaults than fetch, but it still fails if the server returns malformed JSON — it just gives a clearer message about whether it was a network issue, an empty body or a parse problem. Once you know the JSON is the problem, repair it with the tool above or our JSON validator.
Is my JSON sent to a server?
Broken JSON is sent to our server, which uses an AI service to rebuild it, so leave out passwords, tokens or anything private. JSON that already parses is recognised in your browser and never sent. Nothing is kept — reloading the page starts with an empty editor.