Fix "Unexpected End of JSON Input" Error - JSON Parser & Debugger
Free online tool to fix "Unexpected end of JSON input" errors in JavaScript fetch, API calls, and Node.js applications. Debug empty responses and truncated JSON data.
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?
This error occurs when JavaScript's JSON.parse() method receives incomplete, empty, or truncated JSON data. It commonly happens with fetch API calls when the server returns an empty response, HTML error page, or network interruption cuts off the data mid-transmission.
How do I fix this error in fetch API?
Always check response.ok before calling .json(). Use response.text() first to inspect the raw response, then verify it's not empty before parsing. Check the Content-Type header to ensure the server is actually sending JSON. Use our tool above to validate and fix your JSON data.
Why does my API return an empty response?
APIs may return empty responses due to CORS errors, authentication failures, server errors (500), resource not found (404), or incorrect request methods. Check your browser's DevTools Network tab to see the actual HTTP status code and response headers. The server might be returning an error page in HTML format instead of JSON.
Can I prevent this error with try-catch?
Yes, but try-catch only handles the error after it occurs. It's better to prevent it by validating the response first. Wrap your JSON parsing in try-catch as a safety net, but also add checks for empty responses and non-200 status codes before attempting to parse. This gives you better error messages and control over failure scenarios.
Does this error happen with axios or other libraries?
Axios and other HTTP libraries handle JSON parsing automatically and have better default error handling than fetch. However, they can still throw similar errors if the server returns malformed JSON. They typically provide more detailed error messages that help identify whether it's a network issue, empty response, or parsing problem. Once you identify the issue, you can validate your JSON or use our JSON fixer to repair it.
How can I debug this error in production?
Add logging to capture the raw response text before parsing. Log the HTTP status code, Content-Type header, and response length. Use monitoring tools like Sentry or Datadog to track parsing errors in production. Consider implementing retry logic with exponential backoff for transient network errors.