Unexpected end of JSON input: Causes and Fixes

Dec 2, 2026 · 9 min read

Unexpected end of JSON input means the parser got empty or cut-off text: 204 responses, HEAD requests, truncated downloads and streams. How to find which.

The asset register has a "Retire laptop" button. Click it, the laptop disappears from the list on the next refresh, and a red toast says Something went wrong. The console has the real message:

text
SyntaxError: Unexpected end of JSON input

The delete worked. The API answered 204 No Content, exactly as it should, and the front end called res.json() on a response that has no body by definition. The parser was handed an empty string and complained that the JSON ended before it started.

That is the most common way to get this error, but not the only one. This article walks through every cause I have hit in practice (empty bodies, 204s, HEAD requests, truncated downloads and streams parsed in pieces), shows each one failing for real, and ends with a small helper that tells you which one you have.

What the parser is telling you

Unexpected end of JSON input is what V8, the engine in Chrome, Edge and Node, says when the text runs out while it still expects a value. Firefox phrases it as JSON.parse: unexpected end of data, one of the messages on MDN's JSON.parse error reference, and Python's json module says Expecting value: line 1 column 1 (char 0) for an empty string. Here is the same laptop record cut off at different points, run in Node 22:

js
const record = '{"assetId":"7340196284512039415","model":"ThinkPad T14 Gen 5","tags":["finance","london"]}';
const cutAfter = (marker) => record.slice(0, record.indexOf(marker) + marker.length);

const inputs = [
  '',                        // empty body
  '   \n',                   // only whitespace
  cutAfter('"assetId":'),    // cut right after a colon
  cutAfter('"tags":['),      // cut right after an opening bracket
  cutAfter('"Think'),        // cut inside a string
  undefined,                 // a variable that was never set
];

for (const text of inputs) {
  try {
    JSON.parse(text);
  } catch (err) {
    console.log((JSON.stringify(text) ?? 'undefined').slice(-16).padEnd(16), '=>', err.message);
  }
}
text
""               => Unexpected end of JSON input
"   \n"          => Unexpected end of JSON input
"{\"assetId\":"  => Unexpected end of JSON input
 5\",\"tags\":[" => Unexpected end of JSON input
model\":\"Think" => Unterminated string in JSON at position 47 (line 1 column 48)
undefined        => "undefined" is not valid JSON

Two things stand out. An empty or whitespace-only string gives exactly this error, which is why it nearly always means "there was no body". And a document cut in the middle can give other messages depending on where the cut lands: inside a string you get Unterminated string, after a colon or an opening bracket you get Unexpected end. Treat them as one family. For contrast, JSON.parse(null) returns null without any error, so a missing localStorage key does not throw at all; it just hands you a null you might not expect.

Reproducing the causes against a real server

Here is a small stand-in for the asset register API. It does the right thing for a delete and a HEAD request, and the wrong thing in three other places:

js
// A stand-in for the IT asset register API.
import http from 'node:http';

const assets = Array.from({ length: 2000 }, (_, i) => ({
  serial: `PF4X${String(i).padStart(4, '0')}`,
  model: i % 2 ? 'ThinkPad T14 Gen 5' : 'Latitude 7450',
}));
const body = JSON.stringify({ assets });

export const server = http.createServer((req, res) => {
  if (req.method === 'DELETE') {                       // asset retired: nothing to return
    res.writeHead(204);
    return res.end();
  }
  if (req.url === '/api/assets/summary') {             // a handler that forgot to send its body
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end();
  }
  if (req.url === '/api/assets/export-cut') {          // a proxy timed out and ended the response early
    res.writeHead(200, { 'Content-Type': 'application/json' });
    return res.end(body.slice(0, 5000));
  }
  if (req.url === '/api/assets/export-dropped') {      // the connection died mid-download
    res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) });
    res.write(body.slice(0, 5000));
    setTimeout(() => res.socket.destroy(), 50);
    return;
  }
  res.writeHead(200, { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) });
  res.end(req.method === 'HEAD' ? undefined : body);   // HEAD: same headers, never a body
});

And the client code most of us write by default:

js
import { server } from './server.mjs';
await new Promise(r => server.listen(0, r));
const base = `http://localhost:${server.address().port}/api/assets`;

const calls = [
  ['DELETE /api/assets/PF4X0042', () => fetch(`${base}/PF4X0042`, { method: 'DELETE' })],
  ['HEAD /api/assets', () => fetch(base, { method: 'HEAD' })],
  ['GET /api/assets/summary', () => fetch(`${base}/summary`)],
  ['GET /api/assets/export-cut', () => fetch(`${base}/export-cut`)],
  ['GET /api/assets/export-dropped', () => fetch(`${base}/export-dropped`)],
];
for (const [label, call] of calls) {
  try {
    const res = await call();
    await res.json();
    console.log(label.padEnd(31), 'OK');
  } catch (err) {
    console.log(label.padEnd(31), `${err.name}: ${err.message}`);
  }
}
server.close();
text
DELETE /api/assets/PF4X0042     SyntaxError: Unexpected end of JSON input
HEAD /api/assets                SyntaxError: Unexpected end of JSON input
GET /api/assets/summary         SyntaxError: Unexpected end of JSON input
GET /api/assets/export-cut      SyntaxError: Unterminated string in JSON at position 5000 (line 1 column 5001)
GET /api/assets/export-dropped  TypeError: terminated

Empty bodies and 204 No Content

A 204 response carries no content, and the same goes for 205 and 304. Response.json() does not check the status first; it reads the body, gets an empty string and parses it. The summary route shows the server-side version of the bug: a handler that sets a JSON content type and then never writes anything, usually because an early return skipped the line that sends the data.

HEAD requests

HEAD asks for the headers a GET would return and nothing else. People use it to check that an export exists or to read its Content-Length before downloading. Calling .json() on that response will always fail, even though the headers say application/json. A shared request() wrapper that always parses is the usual culprit.

Truncated downloads

The export-cut route stands for a response that ended early but cleanly: a proxy that hit its timeout, a body size limit on a gateway, or a file that was still being written when you read it. The status is 200 and the headers look fine, but the text stops at byte 5,000 of 97,012. The same thing happens without any network at all when JSON is stored in a column or field with a length limit, such as a VARCHAR(255) or a cookie, and gets cut on save.

Notice that a connection that drops outright does not give a JSON error. fetch rejects with TypeError: terminated while reading the body, before JSON.parse ever runs. If you see a JSON error instead, something on the way ended the response on purpose.

Streams parsed in pieces

The last cause is in your own code. When you read a response as a stream, each chunk is however many bytes the network delivered, and chunk edges do not line up with JSON records. Parse a chunk on its own and you are parsing half an object:

js
import http from 'node:http';

// The server streams one JSON object per line (NDJSON). Network chunks do not respect lines.
const server = http.createServer(async (req, res) => {
  res.writeHead(200, { 'Content-Type': 'application/x-ndjson' });
  const text = ['PF4X0001', 'PF4X0002', 'PF4X0003']
    .map(serial => JSON.stringify({ serial, status: 'in-stock' }) + '\n').join('');
  for (const piece of [text.slice(0, 30), text.slice(30, 70), text.slice(70)]) {
    res.write(piece);
    await new Promise(r => setTimeout(r, 20));
  }
  res.end();
});
await new Promise(r => server.listen(0, r));
const url = `http://localhost:${server.address().port}/api/assets/stream`;

// Wrong: parse each chunk as it arrives.
const decoder = new TextDecoder();
for await (const chunk of (await fetch(url)).body) {
  try { JSON.parse(decoder.decode(chunk, { stream: true })); }
  catch (err) { console.log('chunk:', err.message); }
}

// Right: buffer, split on newlines, keep the unfinished tail for the next chunk.
let buffer = '';
const rows = [];
const decoder2 = new TextDecoder();
for await (const chunk of (await fetch(url)).body) {
  buffer += decoder2.decode(chunk, { stream: true });
  const lines = buffer.split('\n');
  buffer = lines.pop();                 // may be half a record
  for (const line of lines) if (line.trim()) rows.push(JSON.parse(line));
}
if (buffer.trim()) throw new Error(`stream ended mid-record: ${buffer}`);
console.log(rows.map(r => r.serial).join(', '));
server.close();
text
chunk: Unexpected end of JSON input
chunk: Unexpected non-whitespace character after JSON at position 10 (line 1 column 11)
chunk: Unexpected non-whitespace character after JSON at position 3 (line 1 column 4)
PF4X0001, PF4X0002, PF4X0003

The fix is to buffer: append each chunk to a string, split on newlines, parse the complete lines and keep the unfinished tail for next time. If the stream ends with something still in the buffer, the server stopped mid-record, and that deserves its own error message rather than a parse failure.

A helper that knows the difference

Read the body as text with Response.text(), decide whether an empty body is allowed, and only then parse. When parsing fails, report the size and how the text ends, because that is what tells a cut-off download apart from a bug in the server's output:

js
const NO_BODY = new Set([204, 205, 304]);

export async function readJson(res, { method = 'GET' } = {}) {
  // Some responses never have a body. Say so, instead of parsing nothing.
  if (method === 'HEAD' || NO_BODY.has(res.status)) return null;

  const text = await res.text();  // a dropped connection rejects here with "terminated"
  if (text.trim() === '') {
    throw new Error(`${res.status} ${res.url}: empty body where JSON was expected`);
  }
  try {
    return JSON.parse(text);
  } catch (err) {
    const expected = res.headers.get('content-length');
    const encoded = res.headers.get('content-encoding');
    const size = new TextEncoder().encode(text).length;
    const short = expected && !encoded && size < Number(expected) ? `, expected ${expected}` : '';
    throw new Error(`${res.status} ${res.url}: invalid JSON after ${size} bytes${short} ` +
      `(${err.message}). Ends with: ${JSON.stringify(text.slice(-30))}`);
  }
}
js
import { server } from './server.mjs';
import { readJson } from './read-json.mjs';
await new Promise(r => server.listen(0, r));
const base = `http://localhost:${server.address().port}/api/assets`;

const calls = [
  [`${base}/PF4X0042`, { method: 'DELETE' }],
  [base, { method: 'HEAD' }],
  [`${base}/summary`, {}],
  [`${base}/export-cut`, {}],
  [base, {}],
];
for (const [url, options] of calls) {
  try {
    const res = await fetch(url, options);
    const data = await readJson(res, options);
    console.log('OK  ', options.method ?? 'GET', data === null ? 'no body' : `${data.assets.length} assets`);
  } catch (err) {
    console.log('FAIL', err.message.replace(base, '/api/assets'));
  }
}
server.close();
text
OK   DELETE no body
OK   HEAD no body
FAIL 200 /api/assets/summary: empty body where JSON was expected
FAIL 200 /api/assets/export-cut: invalid JSON after 5000 bytes (Unterminated string in JSON at position 5000 (line 1 column 5001)). Ends with: "F4X0102\",\"model\":\"Latitude 745"
OK   GET 2000 assets

The Content-Length comparison only runs when the response is not compressed, because Content-Length counts the bytes on the wire, not the decoded text. When it does apply, a message like "invalid JSON after 5000 bytes, expected 97012" settles the question in one line.

The same idea in Python with requests, where r.json() on a 204 raises JSONDecodeError:

python
import requests

BASE = "http://localhost:8741/api/assets"

r = requests.delete(f"{BASE}/PF4X0042")
try:
    r.json()
except requests.exceptions.JSONDecodeError as e:
    print(r.status_code, "JSONDecodeError:", e)

def read_json(r):
    if r.status_code in (204, 205, 304) or r.request.method == "HEAD":
        return None
    if not r.content.strip():
        raise ValueError(f"{r.status_code} {r.url}: empty body where JSON was expected")
    return r.json()

print(read_json(requests.delete(f"{BASE}/PF4X0042")))
print(len(read_json(requests.get(BASE))["assets"]), "assets")
text
204 JSONDecodeError: Expecting value: line 1 column 1 (char 0)
None
2000 assets

Fixing it on the server side

Clients are easier to fix when the API is consistent. Pick one rule per endpoint and stick to it: either 204 with no body and no Content-Type, or 200 with a real JSON body, even if it is only {"retired": true}. The worst combination is the one the summary route shows, a 200 that promises JSON and sends nothing, because no client-side check can tell it apart from a genuine failure.

For large exports, set a Content-Length when you can, or stream NDJSON so that a cut only loses the last record instead of making the whole document unreadable. And if a proxy or gateway sits in front of the API, check its response size and timeout limits against your biggest export. A limit that is just above today's largest payload is the one that starts truncating responses six months from now.

Checking a payload by hand

When the error comes from a file or a saved response rather than live code, paste the text into the JSON validator. For a payload that stops after a comma or a bracket it reports "The JSON ends before everything is closed. Look for a missing } or ]." with the line and column where the text ran out, and for one that stops inside a value it says the string is never closed. Either way you see exactly where the cut is, which is faster than scrolling to the end of a 97 KB line. Once you have a complete copy, the online JSON parser shows the records as a table so you can check the last few made it through.

Wrapping up

  • Unexpected end of JSON input almost always means the text was empty. Look at the status code and the request method before anything else.
  • Never call .json() on 204, 205 or 304 responses, or on any HEAD response. Return null or skip parsing.
  • If a body that should be JSON is empty, it is a server bug: find the handler that set the header and sent nothing.
  • A body that stops early is a truncation problem: compare its size with Content-Length, and look at proxies, size limits and storage columns.
  • When you read streams, buffer up to a newline before parsing. A chunk is not a record.

Read as text, decide what an empty body means for that endpoint, then parse. With that order the error stops being a mystery, and the toast can say something more useful than "Something went wrong".

← All JSON articles Browse all categories →