go encoding_error ai_generated true

json: cannot unmarshal object into Go value of type []main.Foo

ID: go/json-cannot-unmarshal-object-into-go-value-of-type-slice

Also available as: JSON · Markdown · 中文
92%Fix Rate
86%Confidence
1Evidence
2023-08-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
Go 1.20 active
Go 1.21 active
Go 1.22 active

Root Cause

JSON input is an object (e.g., {}) but the target Go type is a slice, causing a type mismatch during unmarshaling.

generic

中文

JSON 输入是一个对象(例如 {}),但目标 Go 类型是切片,导致反序列化期间类型不匹配。

Official Documentation

https://pkg.go.dev/encoding/json#UnmarshalTypeError

Workarounds

  1. 90% success Change the target type to a struct that matches the JSON object: type Foo struct { ... } then unmarshal into &foo.
    Change the target type to a struct that matches the JSON object: type Foo struct { ... } then unmarshal into &foo.
  2. 85% success If the JSON is expected to be an array, fix the JSON source to output an array instead of an object.
    If the JSON is expected to be an array, fix the JSON source to output an array instead of an object.
  3. 80% success Use json.RawMessage to inspect the JSON structure first, then unmarshal conditionally: var raw json.RawMessage; json.Unmarshal(data, &raw); if raw[0] == '{' { ... } else if raw[0] == '[' { ... }
    Use json.RawMessage to inspect the JSON structure first, then unmarshal conditionally: var raw json.RawMessage; json.Unmarshal(data, &raw); if raw[0] == '{' { ... } else if raw[0] == '[' { ... }

中文步骤

  1. Change the target type to a struct that matches the JSON object: type Foo struct { ... } then unmarshal into &foo.
  2. If the JSON is expected to be an array, fix the JSON source to output an array instead of an object.
  3. Use json.RawMessage to inspect the JSON structure first, then unmarshal conditionally: var raw json.RawMessage; json.Unmarshal(data, &raw); if raw[0] == '{' { ... } else if raw[0] == '[' { ... }

Dead Ends

Common approaches that don't work:

  1. 80% fail

    UseNumber() only affects number decoding, not structural type mismatches like object vs slice.

  2. 50% fail

    If the JSON is an array, wrapping in a struct will cause a different mismatch; the fix must match the actual JSON structure.

  3. 60% fail

    RawMessage just delays the error; you still need to unmarshal into the correct type later.