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

Also available as: JSON · Markdown
90%Fix Rate
92%Confidence
50Evidence
2023-01-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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.

generic

Workarounds

  1. 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

    Sources: https://pkg.go.dev/encoding/json#Number

  2. 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))
    }

    Sources: https://pkg.go.dev/encoding/json#Unmarshaler

Dead Ends

Common approaches that don't work:

  1. 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: