Loading JSON Fixer...
Please wait a moment

How to Fix "Unexpected End of JSON Input" Error

Step 1

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.

Empty Response: API returns empty string or null instead of valid JSON
Network Error: Connection interrupted mid-transmission, causing truncated JSON
Wrong Content Type: Server returns HTML error page (404, 500) instead of JSON
Incomplete JSON: Response body is truncated or malformed due to server errors

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"
Step 2

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:

Check response status: Verify the API returns 200 status before parsing JSON
Inspect response text: Use response.text() to see raw response data
Check Content-Type: Ensure server sends application/json header
Test in browser DevTools: Use Network tab to inspect actual API response

Common 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().

❌ Problem: response.json() on empty string
✅ Solution: Check if response.ok and text length > 0

2. Server Returns HTML Error Page

When APIs fail (404, 500), servers often return HTML error pages instead of JSON, which breaks JSON parsing.

❌ Problem: Parsing "<!DOCTYPE html>..." as JSON
✅ Solution: Verify Content-Type header is application/json

3. Truncated JSON Response

Network interruptions or server timeouts can cut off JSON mid-transmission, leaving incomplete data.

❌ Problem: {"data": "incomplete...
✅ Solution: Add network error handling and retry logic

4. CORS or Authentication Errors

CORS or auth failures may return empty responses or error pages that can't be parsed as JSON.

❌ Problem: CORS error returns empty response
✅ Solution: Check response.ok before parsing
Step 3

Implement Proper Error Handling

Add defensive checks to prevent "Unexpected end of JSON input" errors in your code:

Validate before parsing: Check response status and content type before calling .json()
Handle empty responses: Return default values when response is empty
Add try-catch blocks: Catch parsing errors gracefully with meaningful error messages
Log for debugging: Log response text when JSON parsing fails

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.