go serialization_error ai_generated true

json: cannot unmarshal string into Go struct field X of type int

ID: go/json-unmarshal-wrong-type

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

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
1 active

Root Cause

JSON field type doesn't match Go struct type. API returns string '123' but struct expects int.

generic

Workarounds

  1. 90% success Use json.Number or custom UnmarshalJSON for flexible types
    type MyStruct struct {
        Count json.Number `json:"count"`
    }

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

  2. 92% success Match struct field types to actual JSON — use string if API sends strings
    type Response struct {
        Count string `json:"count"` // API sends "42" as string
        // Not: Count int `json:"count"` which would fail on "42"
    }
    
    // Or use json.Number for flexible numeric handling:
    type Response struct {
        Count json.Number `json:"count"`
    }
    // Then: count, _ := resp.Count.Int64()

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

  3. 88% success Use string tag for numeric fields that come as strings: `json:"id,string"`
    `json:"id,string"`

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

Dead Ends

Common approaches that don't work:

  1. Use interface{} for all struct fields 75% fail

    Loses all type safety — every field needs type assertion

Error Chain

Frequently confused with: