SyntaxError: Unexpected end of JSON input

This error means the parser ran out of text before the JSON was complete: the input was empty, or it was cut off. Paste what you received to see where it stops. Repair JSON closes the open strings and brackets so you can inspect what did arrive, and the guide below fixes the cause in fetch, axios, Node.js and Go.

Ctrl/⌘+Enter finds, +Shift repairs

What does "Unexpected end of JSON input" mean?

The parser reached the end of the string while it was still expecting more: a value, a closing ] or }, or the rest of a string. Nothing in the text is "wrong" as such; there is just not enough of it. There are only two root causes:

The box above tells you which one you have. An empty input gets an explanation instead of a repair. A truncated input gets the line and column where the text stops, and Repair JSON closes the open strings and brackets so you can see how much data actually arrived. Repair cannot invent the missing data, so treat it as a way to inspect a broken response, not as the fix.

SyntaxError: Unexpected end of JSON input from fetch and response.json()

Most people meet this error from fetch. response.json() reads the whole body and runs JSON.parse on it, so any response without a JSON body rejects with SyntaxError: Unexpected end of JSON input in Chrome and Node.js, and JSON.parse: unexpected end of data at line 1 column 1 of the JSON data in Firefox. Common cases:

JSON.parse('') and whitespace-only strings

An empty string, or a string of only spaces and line breaks, is not valid JSON. JSON.parse('') and JSON.parse(' ') both throw Unexpected end of JSON input. It shows up when reading a file that exists but is empty, an environment variable set to nothing, an empty localStorage value, or a form field. If "nothing" is a valid state in your app, check for it before parsing and choose a default.

const raw = localStorage.getItem('settings');      // null if missing, '' if empty
const settings = raw && raw.trim() ? JSON.parse(raw) : {};

Truncated payloads: when the JSON stops part-way

If the text has content but stops early, something cut it off. Check the length of what you received against the Content-Length header or the file size. Typical culprits are reverse-proxy or serverless response size limits, a request timeout that closes the connection, a logger that truncates long lines, copying from a terminal that clipped the output, and a process that reads a file while another process is still writing it.

Note that current V8 (Chrome, Node.js 20+) only says "Unexpected end of JSON input" when the text stops where a value was expected, for example after [, , or :. If the text stops after a complete value, it reports the next expected character instead, with a position equal to the length of your string:

Input ends withCurrent V8 message
{"users": [{"id": 1},Unexpected end of JSON input
{"data":Unexpected end of JSON input
{"count": 2Expected ',' or '}' after property value in JSON at position 11
[1, 2Expected ',' or ']' after array element in JSON at position 5
{"name": "Alan TurUnterminated string in JSON at position 18

All five are the same problem. If the position in the message equals the length of the string, the JSON was cut off.

Streaming: parsing before the body is complete

In Node.js, an HTTP response arrives in chunks. Calling JSON.parse inside the data handler parses a fragment and fails. Collect the chunks and parse once, on end:

let body = '';
res.setEncoding('utf8');
res.on('data', chunk => { body += chunk; });     // do not parse here
res.on('end', () => {
  const data = body.trim() ? JSON.parse(body) : null;
});

For newline-delimited JSON (NDJSON) and server-sent events, such as streamed LLM output, each message is one line. Buffer the text and only parse complete lines, because a chunk can end in the middle of a line:

let buf = '';
for await (const chunk of textStream) {
  buf += chunk;
  let nl;
  while ((nl = buf.indexOf('\n')) !== -1) {
    const line = buf.slice(0, nl).trim();
    buf = buf.slice(nl + 1);
    if (line) handle(JSON.parse(line));
  }
}

If an LLM stream stops early, the last object is truncated. LLM JSON repair closes it and also strips Markdown fences and chatter around the JSON.

Safe parsing code for fetch, axios and Node.js

fetch

async function getJSON(url, options) {
  const res = await fetch(url, options);
  const text = await res.text();                 // read the body once
  if (!res.ok) throw new Error('HTTP ' + res.status + ': ' + text.slice(0, 200));
  if (!text.trim()) return null;                 // 204, HEAD, empty body
  try {
    return JSON.parse(text);
  } catch (err) {
    throw new Error('Invalid JSON (' + text.length + ' chars) from ' + url + ': ' + err.message);
  }
}

axios

axios parses JSON for you and does not throw on an empty body: response.data is just an empty string. The error appears when your code then calls JSON.parse(response.data) on that empty string. Do not parse it again:

const res = await axios.delete('/api/items/42');
const data = res.data === '' ? null : res.data;  // already parsed when there is a body

Node.js files

Reading a JSON file while it is being written gives an empty or partial string. Write to a temporary file and rename it, which replaces the file in one step:

const fs = require('fs');
function readJSON(file, fallback) {
  let text;
  try { text = fs.readFileSync(file, 'utf8'); }
  catch (e) { if (e.code === 'ENOENT') return fallback; throw e; }
  return text.trim() ? JSON.parse(text) : fallback;
}
function writeJSON(file, value) {
  fs.writeFileSync(file + '.tmp', JSON.stringify(value, null, 2));
  fs.renameSync(file + '.tmp', file);           // readers never see a half-written file
}

Python

Python's message is Expecting value: line 1 column 1 (char 0), and requests raises it from response.json() on an empty body. Check response.status_code != 204 and response.content before calling it.

unexpected end of JSON input in Go (golang)

Go's encoding/json uses the same words in lowercase. json.Unmarshal returns unexpected end of JSON input (a *json.SyntaxError) for both empty and truncated input. json.Decoder reports the same situations differently: EOF for an empty body and unexpected EOF for a truncated one.

body, err := io.ReadAll(resp.Body)
if err != nil {
    return err
}
if len(bytes.TrimSpace(body)) == 0 {
    return fmt.Errorf("empty response body (status %d)", resp.StatusCode)
}
if err := json.Unmarshal(body, &out); err != nil {
    return fmt.Errorf("decode %d bytes: %w", len(body), err)
}

Common Go causes: reading resp.Body twice (the first io.ReadAll drains it, so the second read is empty), unmarshalling a 204 response, passing a nil or zero-length slice, and decoding buf instead of buf[:n] after a single conn.Read, which may return only part of the message. With json.NewDecoder(r).Decode(&v), treat io.EOF as "no body" if that is allowed.

The same error in other languages

Language / parserEmpty inputTruncated, e.g. {"a":1
JavaScript (V8: Chrome, Node.js)Unexpected end of JSON inputExpected ',' or '}' after property value in JSON at position 6 (older V8: Unexpected end of JSON input)
FirefoxJSON.parse: unexpected end of data at line 1 column 1 of the JSON dataJSON.parse: end of data after property value in object
Python jsonExpecting value: line 1 column 1 (char 0)Expecting ',' delimiter: line 1 column 7 (char 6)
Go json.Unmarshalunexpected end of JSON inputunexpected end of JSON input
Go json.DecoderEOFunexpected EOF
Java (Jackson)No content to map due to end-of-inputUnexpected end-of-input: expected close marker for Object
PHP json_last_error_msg()Syntax errorSyntax error

How to fix it, step by step

  1. Log the length of the text you are parsing, and the HTTP status. Length 0 means an empty body: handle it before parsing.
  2. If the length is not 0, paste the text above. Look at where it stops, and compare the length with Content-Length or the file size.
  3. Find what cut it off: a size limit, a timeout, partial stream parsing, or a concurrent write. Fix that, then parse the full text.
  4. If you only need to salvage what arrived, Repair JSON closes the structure, and keeps large numbers such as 64-bit IDs exactly.

Frequently asked questions

What does "Unexpected end of JSON input" mean?

The parser reached the end of the text before the JSON was complete. Either the input was empty, for example an empty response body, or it was truncated part-way through an object, array or string.

Why does response.json() throw "Unexpected end of JSON input"?

The response has no body. This happens with 204 No Content, HEAD requests, 304 responses, error responses without a body, and fetch with mode no-cors, which hides the body. Read the body with res.text(), check it is not empty, then parse it.

Does JSON.parse("") throw an error?

Yes. An empty string is not valid JSON, so JSON.parse("") throws SyntaxError: Unexpected end of JSON input. A string that contains only spaces or line breaks throws the same error.

Why does Chrome report "Expected ',' or '}' after property value" for truncated JSON?

Current V8 only says Unexpected end of JSON input when the text stops where a value was expected. If it stops after a complete value, it names the character it expected next, at a position equal to the length of the string. Both mean the JSON was cut off.

How do I fix "unexpected end of JSON input" in Go?

Check that the body is not empty before calling json.Unmarshal, make sure you read resp.Body only once, and pass only the bytes you actually read (buf[:n]). With json.Decoder an empty body returns io.EOF and a truncated one returns unexpected EOF.

Can truncated JSON be repaired?

The structure can: Repair JSON on this page closes open strings, arrays and objects so the text parses. The missing data cannot be recovered, so use the repair to inspect what arrived and fix the cause of the truncation.

Is the JSON I paste uploaded?

No. The check and the repair run entirely in your browser.