JSON

End of JSON Input Error: Causes and Solutions

📅 December 14, 2025 ⏱️ 2 min read 👁️ 7 views 🏷️ JSON

The "Unexpected end of JSON input" error occurs when the JSON parser reaches the end of the data before finding a complete, valid JSON structure. This guide explains why it happens and how to fix it.

What Does This Error Mean?

This error indicates that your JSON is incomplete. The parser was expecting more data but reached the end of the string:


// Error examples
JSON.parse('');           // Unexpected end of JSON input
JSON.parse('{"name":');   // Unexpected end of JSON input
JSON.parse('[1, 2,');     // Unexpected end of JSON input
JSON.parse('{"a":');      // Unexpected end of JSON input

Common Causes

1. Empty Response from API


// API returns empty body
fetch('/api/data')
  .then(res => res.text())  // Empty string
  .then(text => JSON.parse(text))  // Error!

// Solution: Check for empty response
fetch('/api/data')
  .then(res => res.text())
  .then(text => {
    if (!text) return null;
    return JSON.parse(text);
  });

2. Truncated Response


// Network timeout cuts off the response
// Received: {"users":[{"name":"John"},{"name":"Ja
// Missing: ne"}]}

// Solution: Verify Content-Length matches body
fetch('/api/data')
  .then(res => {
    const contentLength = res.headers.get('content-length');
    return res.text().then(text => {
      if (contentLength && text.length < parseInt(contentLength)) {
        throw new Error('Response truncated');
      }
      return JSON.parse(text);
    });
  });

3. File Read Issues


# File was not fully written
import json

# Problem: File ends abruptly
# {"config": {
#   "debug": true,
#   "port": 30   <- File ends here

# Solution: Validate JSON structure
def safe_load_json(filepath):
    try:
        with open(filepath, 'r') as f:
            return json.load(f)
    except json.JSONDecodeError as e:
        print(f"Invalid JSON: {e}")
        return None

4. Database Text Truncation


-- VARCHAR too short truncates JSON
CREATE TABLE configs (
  data VARCHAR(100)  -- Too short!
);

-- JSON gets cut off at 100 characters
-- Solution: Use TEXT or JSON column type
CREATE TABLE configs (
  data TEXT  -- Or JSON in PostgreSQL/MySQL
);

5. Logging Truncation


# Log systems often truncate long strings
import logging

# This might get truncated
logging.info(f"Response: {large_json_string}")

# Solution: Log to file or use structured logging

How to Debug

Paste your JSON into our JSON formatter online to see exactly where it is incomplete and what is missing.


// Debug helper
function debugJson(str) {
  console.log('Length:', str.length);
  console.log('First 50 chars:', str.substring(0, 50));
  console.log('Last 50 chars:', str.substring(str.length - 50));
  
  // Check for balanced brackets
  const opens = (str.match(/[{\[]/g) || []).length;
  const closes = (str.match(/[}\]]/g) || []).length;
  console.log(`Brackets: ${opens} opening, ${closes} closing`);
  
  try {
    JSON.parse(str);
    console.log('Valid JSON');
  } catch (e) {
    console.log('Error:', e.message);
  }
}

Prevention Strategies

Always Validate Before Parsing


function safeJsonParse(str) {
  if (!str || typeof str !== 'string') {
    return { error: 'Input is empty or not a string', data: null };
  }
  
  const trimmed = str.trim();
  if (!trimmed) {
    return { error: 'Input is empty after trimming', data: null };
  }
  
  // Basic structure check
  if (!(trimmed.startsWith('{') || trimmed.startsWith('['))) {
    return { error: 'Does not start with { or [', data: null };
  }
  
  try {
    return { error: null, data: JSON.parse(trimmed) };
  } catch (e) {
    return { error: e.message, data: null };
  }
}

Key Takeaways

  • Always check for empty responses before parsing
  • Use proper column types in databases for JSON
  • Handle network timeouts gracefully
  • Validate JSON structure before storing

Use our JSON formatter online to validate your JSON and identify what is missing or incomplete.

🏷️ Tags:
end of json input json error incomplete json truncated json

📚 Related Articles