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?

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.