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
92%Fix Rate
86%Confidence
1Evidence
2023-08-05First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 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#UnmarshalTypeErrorWorkarounds
-
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. -
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.
-
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] == '[' { ... }
中文步骤
Change the target type to a struct that matches the JSON object: type Foo struct { ... } then unmarshal into &foo.If the JSON is expected to be an array, fix the JSON source to output an array instead of an object.
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:
-
80% fail
UseNumber() only affects number decoding, not structural type mismatches like object vs slice.
-
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.
-
60% fail
RawMessage just delays the error; you still need to unmarshal into the correct type later.