Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding/json: The result has been changed even an error happened at json.Unmarshal #35454

Closed
brotherbin opened this issue Nov 8, 2019 · 1 comment

Comments

@brotherbin
Copy link

What version of Go are you using (go version)?

go version go1.12.6 darwin/amd64

Does this issue reproduce with the latest release?

Yes, I had try it at go version go1.13 linux/amd64

What operating system and processor architecture are you using (go env)?

go env Output
GOARCH="amd64"
GOBIN="/Users/dobbin/go/bin"
GOCACHE="/Users/dobbin/Library/Caches/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/Users/dobbin/go"
GOPROXY=""
GORACE=""
GOROOT="/usr/local/go"
GOTMPDIR=""
GOTOOLDIR="/usr/local/go/pkg/tool/darwin_amd64"
GCCGO="gccgo"
CC="clang"
CXX="clang++"
CGO_ENABLED="1"
GOMOD="/Users/dobbin/watermirror/code/pdes-mas/go.mod"
CGO_CFLAGS="-g -O2"
CGO_CPPFLAGS=""
CGO_CXXFLAGS="-g -O2"
CGO_FFLAGS="-g -O2"
CGO_LDFLAGS="-L/Users/dobbin/Library/mpich-3.2.1 -lmpich"
PKG_CONFIG="pkg-config"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fdebug-prefix-map=/var/folders/05/5bjcpjgx39j2029gw9q2xq1w0000gn/T/go-build041111828=/tmp/go-build -gno-record-gcc-switches -fno-common"

What did you do?

type A struct {
	Id int `json:"id"`
}

func main() {
	var arr []A
	var str = `[1,2,3]`
	if err := json.Unmarshal([]byte(str), &arr); err != nil {
		fmt.Println(err)
	}
	fmt.Println(arr)
}

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

What did you expect to see?

[]

The variable arr should be a empty slice because an error happened at json.Unmarshal([]byte(str), &arr).

What did you see instead?

[{0} {0} {0}]

The variable arr is a non-empty slice with 3 elements

@bcmills
Copy link
Contributor

bcmills commented Nov 8, 2019

This appears to be working as documented.

Per https://golang.org/pkg/encoding/json/#Unmarshal:

If a JSON value is not appropriate for a given target type, or if a JSON number overflows the target type, Unmarshal skips that field and completes the unmarshaling as best it can. If no more serious errors are encountered, Unmarshal returns an UnmarshalTypeError describing the earliest such error.

@bcmills bcmills closed this as completed Nov 8, 2019
@golang golang locked and limited conversation to collaborators Nov 7, 2020
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants