ENRU

Unexpected end of JSON input: empty or cut-off data

Updated

SyntaxError: Unexpected end of JSON input means the text ran out before a JSON value was complete. The parser read everything it was given. It wasn’t enough. Most of the time it was given nothing at all: an empty response body, a 204, an empty file or variable. Less often the text was cut off halfway. These are different bugs, and the first job is telling them apart.

Where it appears and how it is worded

V8 has used this wording for years, unchanged from Node.js 18 to Node.js 25. When the failing call is response.json(), Chrome sometimes names the method in front of it: in runs on Chrome 156 the same 204 response produced both forms. Other engines say it their own way:

Engine, version checkedMessageNote
Chrome 156, Node.js 18.20, 20.20 and 25.1 (V8)SyntaxError: Unexpected end of JSON inputJSON.parse('') and response.json() on an empty body
Chrome 156, response.json()SyntaxError: Failed to execute 'json' on 'Response': Unexpected end of JSON inputThe same error with the failing method named
Chrome 156, fetch with mode: 'no-cors'SyntaxError: Unexpected end of inputAn opaque response: its body can’t be read at all
Firefox (source: SpiderMonkey)SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
Safari, JavaScriptCore of macOS 27.0.1SyntaxError: JSON Parse error: Unexpected EOFFrom JSON.parse
Safari response.json() (source: WebKit)SyntaxError: The string did not match the expected pattern.WebKit’s generic text for any JSON failure in fetch
React Native, Hermes (source)SyntaxError: JSON Parse error: Unexpected end of input
Python 3.9.6 and 3.14.10json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)See Expecting value
Go 1.25.3, json.Unmarshalunexpected end of JSON inputFor empty and cut-off input alike
Go 1.25.3, json.DecoderEOF for an empty body, unexpected EOF for a cut-off oneerrors.Is(err, io.EOF) tells them apart
Java, Jackson 2.20.1MismatchedInputException: No content to map due to end-of-inputFrom readValue; readTree returns a MissingNode instead
C#, System.Text.Json 10 (runtime 10.0.14)JsonException: The input does not contain any JSON tokens. Expected the input to start with a valid JSON token, when isFinalBlock is true. Path: $ | LineNumber: 0 | BytePositionInLine: 0.Also from GetFromJsonAsync on a 204
PHP 8.5.12Syntax errorCode 4, like any other syntax error
jq 1.7.1 and 1.8.2no message, no output, exit code 0Empty input is zero documents; jq -e exits with 4 instead

Two libraries don’t complain at all: Gson 2.13.2 fromJson("", Map.class) and Newtonsoft.Json 13.0.4 DeserializeObject of an empty string both return null, which moves the failure to the first line that uses the result.

Empty or cut off: measure first

Log the length of the text before parsing it. Zero means nothing arrived; anything else means the text stopped early. The last characters show where.

const res = await fetch(url);
const text = await res.text();
console.log(res.status, res.type, res.headers.get('content-length'), text.length);
console.log(JSON.stringify(text.slice(-80)));

Length 0: there is nothing to parse

  • 204 No Content. RFC 9110 says a 204 response “cannot contain content”, so response.json() on it always fails. DELETE and PUT endpoints often answer 204.
  • An opaque response. mode: 'no-cors' doesn’t fix a cross-origin error, it hides the response: status 0, type is opaque, an empty body. Chrome then says Unexpected end of input. Allow the origin on the server instead; see request modes.
  • A HEAD request. It never has a body.
  • An error without a body. Some servers answer 401, 404 or 502 with nothing at all. Read the status before the body.
  • No response involved. JSON.parse('') on an empty form field, an environment variable read as an empty string, an empty file, a cleared cookie.

Length above 0: the text stopped early

A cut-off document doesn’t always say “end of input”. V8 reports what it expected at the point where the text ran out, so the message depends on where the cut fell:

Text ends withV8 (Node.js 25.1)Python 3.9.6 and 3.14.10
{"id": 42, "name":Unexpected end of JSON inputExpecting value: line 1 column 19 (char 18)
[1, 2, Unexpected end of JSON inputExpecting value: line 1 column 8 (char 7)
{"items": [1, 2Expected ',' or ']' after array element in JSON at position 15 (line 1 column 16)Expecting ',' delimiter: line 1 column 16 (char 15)
{"id": 42, "name": "AdUnterminated string in JSON at position 22 (line 1 column 23)Unterminated string starting at: line 1 column 20 (char 19)

The tell is the position: when it equals the length of the text, the parser hit the end. In a test, parsing the first 65,377-character chunk of a larger Node.js response gave Expected ',' or '}' after property value in JSON at position 65377 (line 1 column 65378). The chunk ended there; the JSON didn’t. Cut-off documents are covered in detail under unclosed bracket and unclosed string.

  • Parsing chunks instead of the body. In Node.js, res.on('data') delivers pieces. Collect them and parse once on 'end', or use fetch and res.json(), which wait for the whole body.
  • A connection closed mid-response. The server crashed, or a proxy hit a timeout or a size limit. Compare Content-Length with the length you received, and find the request in the server log.
  • A log or a terminal that shortens long lines. JSON copied from a log entry is often incomplete.
  • A file read while it was still being written.

Fix: make “no body” a case, not a crash

Decide what an empty body means for your code (usually null, or “nothing changed”) and check for it before parsing. A cut-off body is a real failure: let it throw and log the length. Each snippet was run against a test server answering 204, an empty 200, a full JSON body and a cut-off one.

JavaScript

async function readJson(res) {
  const text = await res.text();
  if (res.status === 204 || text.trim() === '') return null;
  return JSON.parse(text);
}

Python (requests)

def read_json(r):
    if r.status_code == 204 or not r.content.strip():
        return None
    return r.json()

Go

func decodeOptional(r io.Reader, v any) (bool, error) {
	err := json.NewDecoder(r).Decode(v)
	if errors.Is(err, io.EOF) {
		return false, nil
	}
	return err == nil, err
}

Java (HttpClient and Jackson)

static JsonNode readJson(HttpResponse<String> resp) throws IOException {
    String body = resp.body();
    if (resp.statusCode() == 204 || body.isBlank()) return null;
    return mapper.readTree(body);
}

C#

static async Task<T?> ReadJson<T>(HttpResponseMessage resp)
{
    var body = await resp.Content.ReadAsStringAsync();
    if (string.IsNullOrWhiteSpace(body)) return default;
    return JsonSerializer.Deserialize<T>(body);
}

PHP

function readJson(string $body): ?array
{
    if (trim($body) === '') {
        return null;
    }
    return json_decode($body, true, 512, JSON_THROW_ON_ERROR);
}

In shell scripts, jq’s silence on empty input is easy to take for success. curl --fail-with-body exits with code 22 on 4xx and 5xx responses, and jq -e exits with 4 when there was nothing to produce a result from:

curl -sS --fail-with-body https://example.com/api/report | jq -e .

Prevent it

  • APIs: answer either 204 with no body or 200 with a JSON body, and document which. A 200 with an empty body is the worst of both.
  • Clients: branch on the status before reading the body, and treat 204 as null.
  • Never use no-cors for a response you need to read.
  • Large data: stream it as JSON Lines or with a streaming parser instead of parsing chunks by hand.
  • Files: write to a temporary file and rename it into place, so readers never see an empty or half-written document.

Try it

Paste the text into the validator. Empty input is reported as empty; a cut-off document as an unclosed object, array or string, with its line and column.

Related: Unexpected token '<' when the body is HTML, empty input, Expecting value for Python, and the list of JSON errors.

Unexpected end of JSON input FAQ

What does “Unexpected end of JSON input” mean?

The parser reached the end of the text before it had a complete value. Usually the text was empty; sometimes it was cut off partway.

Why does response.json() fail on a 204?

A 204 response has no content by definition, and an empty string is not JSON. Check res.status === 204 first, or read the body with res.text() and parse only text that isn’t empty.

Is an empty string valid JSON?

No. RFC 8259 defines a JSON text as one value with optional whitespace around it, and an empty string contains no value. Two quote marks, "", are valid: that is a string value that happens to be empty.

How do I tell an empty body from a cut-off one?

Log text.length before parsing. Zero means empty. Otherwise compare it with Content-Length and look at the last characters: a body that ends without its closing } or ] was cut.