{FormJSON}
Developer Troubleshooting Guide • JSON Syntax & Streaming

How to Fix "Unexpected end of JSON input"

Diagnosing empty response bodies, truncated JSON payloads, and unclosed brackets in JSON.parse().

Have an incomplete or truncated JSON string?
FormJson Safe Repair can automatically close unclosed brackets and fix malformed syntax.
Repair Incomplete JSON →

01. Why This Error Happens

The JavaScript engine throws SyntaxError: Unexpected end of JSON input when the parser reaches the end of the string while still expecting more tokens.

1. Empty String

Calling JSON.parse("") or parsing an empty HTTP response body.

2. Unclosed Brackets

Payloads like {"items": [1, 2 missing closing ]}.

3. Network Truncation

HTTP connection timed out or socket dropped before all chunks arrived.

02. Handling HTTP 204 No Content & Empty Responses

APIs frequently return HTTP 204 (No Content) or 201 for DELETE/PUT/POST requests. Always check the response status and content-length before invoking response.json():

async function fetchApi(url, options) {
  const res = await fetch(url, options);

  if (!res.ok) {
    throw new Error(`Request failed with status ${res.status}`);
  }

  // Handle 204 No Content or empty responses safely
  if (res.status === 204 || res.headers.get('content-length') === '0') {
    return null;
  }

  const text = await res.text();
  return text ? JSON.parse(text) : null;
}

03. Safe JSON Parse Helper for Local Storage & Configs

When reading from localStorage or reading configuration files from disk, use a defensive wrapper:

function tryParseJson(value, fallback = null) {
  if (!value || typeof value !== 'string') return fallback;
  try {
    return JSON.parse(value);
  } catch (err) {
    console.warn('Malformed JSON payload, using fallback:', err.message);
    return fallback;
  }
}

Frequently Asked Questions

FAQ

What causes 'SyntaxError: Unexpected end of JSON input'?
This error occurs when JSON.parse() is called on an empty string '', an unclosed object or array (e.g. '{"id": 1' missing '}'), or a network payload that was cut off before transmission completed.
Why does fetch() throw unexpected end of JSON input on HTTP 204?
HTTP 204 (No Content) responses have an empty body. Calling 'response.json()' on an empty body always throws this error. You should check 'if (response.status === 204) return null;' first.
How can FormJson Safe Repair fix unexpected end of input?
FormJson's Safe Repair tool automatically detects unclosed braces, brackets, and quotes, appending the necessary matching closures to restore valid JSON syntax.
How do I fix unexpected end of JSON input in Node.js or Express?
Ensure your client sends a non-empty request body with 'Content-Type: application/json', and verify your server middleware ('express.json()') is not parsing empty payloads.

Explore Related Tools & Converters

100% Client-Side