go encoding_error ai_generated true

json: unexpected end of JSON input

ID: go/json-unexpected-end-of-json-input

Also available as: JSON · Markdown · 中文
80%Fix Rate
85%Confidence
1Evidence
2023-09-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
go1.21 active
go1.22 active
go1.23 active

Root Cause

The JSON decoder encountered the end of the input stream before completing the parsing of a valid JSON value.

generic

中文

JSON 解码器在完成有效 JSON 值的解析之前遇到了输入流的结束。

Official Documentation

https://pkg.go.dev/encoding/json#Decoder.Decode

Workarounds

  1. 90% success Check the source of the JSON data to ensure it is complete (e.g., full HTTP response body, complete file read). Use io.ReadAll to read all data before unmarshaling.
    Check the source of the JSON data to ensure it is complete (e.g., full HTTP response body, complete file read). Use io.ReadAll to read all data before unmarshaling.
  2. 85% success Use json.Decoder with a buffered reader and check for io.ErrUnexpectedEOF specifically to provide a better error message.
    Use json.Decoder with a buffered reader and check for io.ErrUnexpectedEOF specifically to provide a better error message.

中文步骤

  1. Check the source of the JSON data to ensure it is complete (e.g., full HTTP response body, complete file read). Use io.ReadAll to read all data before unmarshaling.
  2. Use json.Decoder with a buffered reader and check for io.ErrUnexpectedEOF specifically to provide a better error message.

Dead Ends

Common approaches that don't work:

  1. Adding more fields to the Go struct to match the expected JSON. 80% fail

    The error is about incomplete input, not missing fields; adding fields doesn't fix malformed or truncated data.

  2. Using json.Unmarshal with a string that includes extra whitespace. 70% fail

    Whitespace is ignored by the decoder; the input must be a complete JSON value.