Back to Blog

Fix: "Unexpected End of JSON Input" Error Explained

Complete Guide to Fixing JSON Parse Errors (2026)

Definition: What is the "Unexpected End of JSON Input" Error?

The "Unexpected end of JSON input" error is a JavaScript error that occurs when JSON.parse() or response.json() attempts to parse incomplete, empty, or malformed JSON data. The error indicates that the JSON parser reached the end of the input string before finding a complete, valid JSON structure.

This error typically appears when trying to parse an empty string, a truncated JSON response, or incomplete data. Valid JSON must be a complete object ({...}), array ([...]), or primitive value. An empty string or incomplete JSON structure causes the parser to fail with this specific error message.

The error message "Unexpected end of JSON input" is thrown by JavaScript's built-in JSON parser when it encounters the end of the input string while still expecting more JSON content. This is different from syntax errors, which occur when JSON has invalid characters or structure. This error specifically indicates that the JSON is incomplete or empty.

Key Point: The "Unexpected end of JSON input" error occurs when JSON.parse() receives incomplete or empty data. Valid JSON must be complete - an empty string or truncated JSON will cause this error. Always check if data exists and is complete before parsing.

What: Understanding the JSON Input Error

The "Unexpected end of JSON input" error involves several components:

JSON Parser

JavaScript's JSON.parse() expects complete, valid JSON syntax. It reads the input character by character, building a parse tree. If it reaches the end of input before completing the parse, it throws "Unexpected end of JSON input".

Parser expects complete JSON structure (object, array, or primitive)

Empty Input

An empty string is not valid JSON. When you pass an empty string to JSON.parse(""), the parser finds nothing to parse and immediately throws the error. This is the most common cause of this error.

Empty string: JSON.parse("") throws "Unexpected end of JSON input"

Incomplete Data

Truncated JSON responses from APIs, network interruptions, or incomplete file reads can cause this error. The parser starts parsing but encounters the end of input before finding closing braces, brackets, or complete values.

Example: { "name": "John" (missing closing brace) causes error

Error Handling

Proper error handling checks if data exists and is complete before parsing. Use try-catch blocks, validate response content, check for empty strings, and handle edge cases like 204 No Content responses that have no body.

Always validate data before parsing JSON

Important: Understanding that JSON.parse() requires complete, valid JSON is crucial. Empty strings, incomplete data, or truncated responses will cause this error. Always validate and check data before attempting to parse JSON.

When: When Does This Error Occur?

The "Unexpected end of JSON input" error occurs in these situations:

Empty API Responses

When an API returns an empty response body (like 204 No Content), trying to parse it with response.json() throws this error. Some APIs return empty responses for successful DELETE requests or updates that don't return data.

Parsing Empty Strings

When you try to parse an empty string with JSON.parse(""), the parser finds nothing to parse and immediately throws this error. This happens when variables are initialized as empty strings or when data fetching returns empty content.

Truncated JSON Data

When JSON data is incomplete due to network issues, file read errors, or response streaming problems, the parser encounters the end of input before finding complete JSON structure. This causes the error.

Error Responses

When APIs return error responses without JSON body, or when error handlers try to parse non-JSON error messages, this error occurs. Always check response status and content type before parsing.

Common Scenario: This error most commonly occurs when trying to parse empty API responses, empty strings, or incomplete JSON data. It's especially common with fetch() when APIs return 204 No Content or when error responses don't contain JSON.

How To: Fix the JSON Input Error

Follow these methods to fix the "Unexpected end of JSON input" error:

Method 1: Check for Empty Response Before Parsing

Always validate that response has content before parsing:

Check Response Text First

// Check if response has content before parsing
async function fetchData() {
  const response = await fetch('/api/data');
  
  // Get response as text first
  const text = await response.text();
  
  // Check if text is empty
  if (!text || text.trim() === '') {
    console.log('Empty response');
    return null;
  }
  
  // Parse only if content exists
  try {
    return JSON.parse(text);
  } catch (error) {
    console.error('JSON parse error:', error);
    return null;
  }
}

Check Content-Length Header

async function fetchData() {
  const response = await fetch('/api/data');
  
  // Check content length
  const contentLength = response.headers.get('content-length');
  
  if (contentLength === '0' || !contentLength) {
    // Handle empty response
    return null;
  }
  
  // Safe to parse
  return await response.json();
}

Method 2: Use Try-Catch with Specific Error Handling

Handle the error gracefully with try-catch:

Catch and Handle Empty JSON

async function fetchData() {
  try {
    const response = await fetch('/api/data');
    const data = await response.json();
    return data;
  } catch (error) {
    // Check if it's the "end of JSON input" error
    if (error.message.includes('end of JSON input') || 
        error.message.includes('Unexpected end')) {
      console.log('Empty or incomplete JSON response');
      return null; // or return {}
    }
    // Re-throw other errors
    throw error;
  }
}

Handle 204 No Content Responses

async function deleteItem(id) {
  const response = await fetch('/api/items/' + id, {
    method: 'DELETE'
  });
  
  // 204 No Content has no body
  if (response.status === 204) {
    return null; // Success, but no data
  }
  
  // Only parse if there's content
  if (response.headers.get('content-length') !== '0') {
    try {
      return await response.json();
    } catch (error) {
      if (error.message.includes('end of JSON input')) {
        return null;
      }
      throw error;
    }
  }
  
  return null;
}

Method 3: Provide Default Values

Default Empty Object or Array

// Provide default empty object
function parseJSONSafely(jsonString) {
  try {
    return JSON.parse(jsonString || '{}');
  } catch (error) {
    if (error.message.includes('end of JSON input')) {
      return {}; // Return empty object instead of error
    }
    throw error;
  }
}

// Usage
const data = parseJSONSafely(responseText);

// Or with nullish coalescing
const data = JSON.parse(responseText || '{}');

Method 4: Validate JSON String Before Parsing

Check if String is Valid JSON

function isValidJSON(str) {
  if (!str || str.trim() === '') {
    return false;
  }
  
  try {
    JSON.parse(str);
    return true;
  } catch (e) {
    return false;
  }
}

// Use before parsing
const responseText = await response.text();

if (isValidJSON(responseText)) {
  const data = JSON.parse(responseText);
} else {
  console.log('Invalid or empty JSON');
  // Handle accordingly
}

Method 5: Handle Different Response Types

Check Content-Type Header

async function fetchData() {
  const response = await fetch('/api/data');
  
  // Check content type
  const contentType = response.headers.get('content-type');
  
  // Only parse if it's JSON
  if (contentType && contentType.includes('application/json')) {
    const text = await response.text();
    
    if (text && text.trim()) {
      try {
        return JSON.parse(text);
      } catch (error) {
        console.error('JSON parse error:', error);
        return null;
      }
    }
  }
  
  // Not JSON or empty
  return null;
}

Best Practice: Always check if response has content before parsing, use try-catch to handle errors gracefully, validate JSON strings before parsing, check response status and content-type headers, and provide default values for empty responses. Handle 204 No Content and other empty responses appropriately.

Why: Why This Error Occurs

The "Unexpected end of JSON input" error occurs for several important reasons:

JSON Specification

JSON requires complete, valid syntax. An empty string is not valid JSON according to the JSON specification (RFC 8259). The parser expects at least one complete JSON value (object, array, string, number, boolean, or null), not an empty input.

Parser Behavior

JSON.parse() reads input character by character, building a parse tree. When it reaches the end of input before completing the parse (finding closing braces, brackets, or complete values), it throws this error. This is expected parser behavior for incomplete data.

API Design

Many APIs return empty responses for certain operations (DELETE, 204 No Content). When you try to parse these empty responses as JSON, the parser fails. This is a common scenario that requires proper error handling and response validation.

Data Completeness

Network issues, streaming problems, or file read errors can result in incomplete JSON data. The parser expects complete JSON but receives truncated data, causing this error. Validating data completeness before parsing prevents this issue.

Important: This error is a validation error that occurs when JSON.parse() receives incomplete or empty data. It's a common error in modern web development, especially with API integration. Understanding why it happens helps you write more robust code that handles edge cases properly.

Frequently Asked Questions

What does "Unexpected end of JSON input" error mean?

This error occurs when JSON.parse() receives incomplete or empty JSON data. The parser expects valid JSON but encounters the end of the input before finding complete JSON structure. Common causes include empty responses, truncated data, incomplete API responses, or trying to parse empty strings.

How do I fix "Unexpected end of JSON input" error?

Check if the response is empty before parsing: if (response.trim()) { data = JSON.parse(response) }. Handle empty responses: try { data = JSON.parse(response) } catch(e) { if (e.message.includes("end")) { data = null } }. Verify response content: console.log(response) before parsing. Ensure complete data: wait for full response before parsing. Use optional chaining: JSON.parse(response || "").

Why does JSON.parse() fail with empty string?

JSON.parse() requires valid JSON syntax. An empty string is not valid JSON - it's neither an object {} nor an array []. When you try to parse an empty string, the parser reaches the end of input without finding any JSON structure, causing the "Unexpected end of JSON input" error.

How do I handle empty API responses in fetch?

Check response status and content length before parsing: if (response.ok && response.headers.get("content-length") !== "0") { const data = await response.json() }. Use try-catch: try { const data = await response.json() } catch(e) { if (response.status === 204) { return null } }. Handle 204 No Content responses that have no body. Check response.text() first to see if it's empty.

What is the difference between JSON.parse() and response.json()?

JSON.parse() parses a JSON string, while response.json() is a Fetch API method that reads and parses JSON from a Response object. Both can throw "Unexpected end of JSON input" if the data is incomplete. response.json() automatically handles the response stream, while JSON.parse() requires the full string first.

Share this article with Your Friends, Collegue and Team mates

Stay Updated

Get the latest tool updates, new features, and developer tips delivered to your inbox.

No spam. Unsubscribe anytime. We respect your privacy.

Feedback for Fix Unexpected End of JSON Input Error Guide

Help us improve! Share your thoughts, report bugs, or suggest new features.

Get in Touch

We'd love to hear from you! Write us for any additional feature request, issues, query or appreciation.

Your feedback helps us improve and build better tools for the developer community.