Go version

go version devel go1.24-96f7159705 Tue Jul 30 20:12:39 2024 +0000 linux/amd64

Output of go env in your module/workspace:

GO111MODULE=''
GOARCH='amd64'
GOBIN=''
GOCACHE='/home/dominikh/.cache/go-build'
GOENV='/home/dominikh/.config/go/env'
GOEXE=''
GOEXPERIMENT=''
GOFLAGS=''
GOHOSTARCH='amd64'
GOHOSTOS='linux'
GOINSECURE=''
GOMODCACHE='/home/dominikh/prj/pkg/mod'
GONOPROXY=''
GONOSUMDB=''
GOOS='linux'
GOPATH='/home/dominikh/prj'
GOPRIVATE=''
GOPROXY='https://proxy.golang.org,direct'
GOROOT='/home/dominikh/prj/go'
GOSUMDB='sum.golang.org'
GOTMPDIR=''
GOTOOLCHAIN='auto'
GOTOOLDIR='/home/dominikh/prj/go/pkg/tool/linux_amd64'
GOVCS=''
GOVERSION='devel go1.24-96f7159705 Tue Jul 30 20:12:39 2024 +0000'
GODEBUG=''
GOTELEMETRY='local'
GOTELEMETRYDIR='/home/dominikh/.config/go/telemetry'
GCCGO='gccgo'
GOAMD64='v1'
AR='ar'
CC='gcc'
CXX='g++'
CGO_ENABLED='1'
GOMOD='/home/dominikh/prj/src/example.com/go.mod'
GOWORK=''
CGO_CFLAGS='-O2 -g'
CGO_CPPFLAGS=''
CGO_CXXFLAGS='-O2 -g'
CGO_FFLAGS='-O2 -g'
CGO_LDFLAGS='-O2 -g'
PKG_CONFIG='pkg-config'
GOGCCFLAGS='-fPIC -m64 -pthread -Wl,--no-gc-sections -fmessage-length=0 -ffile-prefix-map=/tmp/nix-shell.pip13R/go-build4163698412=/tmp/go-build -gno-record-gcc-switches'

What did you do?

https://play.golang.org/p/Ypv2xaFDAOs

package main

import (
    "encoding/json"
    "fmt"
)

type Foo struct {
    Bar Bar
}

type Bar struct{}

func (*Bar) UnmarshalJSON(data []byte) error {
    var dst struct {
        K int `json:"k"`
    }
    err := json.Unmarshal(data, &dst)
    fmt.Println(err)
    return err
}

func main() {
    var f Foo
    fmt.Println(json.Unmarshal([]byte(`{"Bar": {"k": "v"}}`), &f))
}

What did you see happen?

json: cannot unmarshal string into Go struct field .k of type int json: cannot unmarshal string into Go struct field Foo.Bar of type int

What did you expect to see?

A less misleading error returned by the call to json.Unmarshal in main. The type of Foo.Bar is not int and we no longer know where the error actually happened.

Comment From: gabyhelp

Related Issues and Documentation

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

Comment From: dominikh

Thanks bot. This is #61337, which was closed as a duplicate of #11858. I disagree with that decision. While they're related by what causes them, they're two different problems, and this issue will probably be easier to fix than #11858.

Comment From: dr2chase

@dsnet @mvdan

Comment From: cagedmantis

cc @rsc

Comment From: j2gg0s

We should join err.Field with d.errContext.FieldContext if err.Field is not empty?

Comment From: gopherbot

Change https://go.dev/cl/605455 mentions this issue: encoding/json: optimize UnmarshalTypeError's field stack for nested unmarshal