json.InvalidUnmarshalError
GoERRORCommonJSON
json: Unmarshal(non-pointer …)
Quick Answer
Always pass a non-nil pointer to json.Unmarshal, e.g. &myStruct not myStruct.
What this means
Returned when json.Unmarshal is called with a non-pointer or nil pointer as the target. The JSON is valid; the issue is the destination argument.
Why it happens
- 1Passing a value type instead of a pointer to Unmarshal
- 2Passing a nil pointer that has not been initialized
Fix
Pass pointer address
Pass pointer address
var v MyStruct err := json.Unmarshal(data, &v) // correct // json.Unmarshal(data, v) is wrong
Why this works
json.Unmarshal requires a pointer so it can modify the value through reflection.
Code examples
Correct usagego
var v MyStruct err := json.Unmarshal(data, &v)
Detectgo
var ie *json.InvalidUnmarshalError
if errors.As(err, &ie) {
log.Printf("bad target type: %v", ie.Type)
}Initialize pointergo
v := new(MyStruct) err := json.Unmarshal(data, v)
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