go
serialization_error
ai_generated
true
json: cannot unmarshal string into Go struct field Foo.Bar of type int
ID: go/json-unmarshal-type-error
90%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| 1 | active | — | — | — |
Root Cause
The JSON field type does not match the Go struct field type. For example, JSON has a string "123" but the Go field is int. The encoding/json package returns *json.UnmarshalTypeError.
genericWorkarounds
-
90% success Use json.Number for fields that may be string or number
decoder := json.NewDecoder(reader) decoder.UseNumber() // or use json.Number type in struct
-
92% success Implement custom UnmarshalJSON to handle flexible input types
func (f *FlexInt) UnmarshalJSON(b []byte) error { var n int if err := json.Unmarshal(b, &n); err == nil { *f = FlexInt(n); return nil } var s string if err := json.Unmarshal(b, &s); err == nil { i, err := strconv.Atoi(s) *f = FlexInt(i); return err } return fmt.Errorf("cannot unmarshal %s", string(b)) }
Dead Ends
Common approaches that don't work:
-
Use interface{} for all struct fields to avoid type mismatches
75% fail
Loses all type safety and requires manual type assertions everywhere the fields are used, creating more bugs
Error Chain
Leads to:
Preceded by:
Frequently confused with: