go type_error ai_generated true

json: cannot unmarshal array into Go value of type struct { Name string }

ID: go/json-cannot-unmarshal-array-into-struct

Also available as: JSON · Markdown · 中文
80%Fix Rate
88%Confidence
0Evidence
2024-03-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1.21 active

Root Cause

JSON data is an array but target Go type is a struct, causing type mismatch.

generic

中文

JSON 数据是数组,但目标 Go 类型是结构体,导致类型不匹配。

Workarounds

  1. 95% success
    Unmarshal into []struct{ Name string } if JSON is array: var data []struct{Name string}; json.Unmarshal([]byte(jsonStr), &data)
  2. 85% success
    Use json.RawMessage to inspect first, then unmarshal accordingly.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    Data not parsed, leads to nil values.

  2. 40% fail

    May not match API contract; breaks other code.