json.UnmarshalTypeError
GoERRORNotableJSON
cannot unmarshal … into Go value of type …
Quick Answer
Type-assert to *json.UnmarshalTypeError to log the Field name and fix the struct definition.
What this means
Returned when a JSON value cannot be stored in the target Go type, such as a JSON string into an int field. Field and Offset identify the problem location.
Why it happens
- 1JSON field type does not match the Go struct field type
- 2Numeric string received where a number was expected
Fix
Type-assert for details
Type-assert for details
var te *json.UnmarshalTypeError
if errors.As(err, &te) {
log.Printf("wrong type for field %s", te.Field)
}Why this works
The Field name guides developers to the struct or JSON property that needs correction.
Code examples
Detectgo
type T struct{ Age int }
var t T
err := json.Unmarshal([]byte(`{"Age":"old"}`), &t)
var te *json.UnmarshalTypeError
errors.As(err, &te)Use json.Numbergo
dec := json.NewDecoder(r) dec.UseNumber() dec.Decode(&v)
Custom unmarshalergo
func (t *T) UnmarshalJSON(b []byte) error {
// custom parsing logic
return nil
}Same error in other languages
Sources
Official documentation ↗
Go standard library
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev