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: duplicate struct tags cause json.Marshal to silently fail #28288

Closed
is8ac opened this issue Oct 19, 2018 · 3 comments

Comments

Projects
None yet
3 participants
@is8ac
Copy link

commented Oct 19, 2018

Please answer these questions before submitting your issue. Thanks!

What did you do?

Marshal a struct containing duplicate struct tags silently produces an empty json struct.

Example:

package main

import (
	"encoding/json"
	"fmt"
)

type demoStruct struct {
	Foo uint8 `json:"baz"`
	Bar uint8 `json:"baz"`
}

func main() {
	fooStruct := demoStruct{Foo: 1, Bar: 2}
	fmt.Println(fooStruct)
	jsonBytes, err := json.Marshal(fooStruct)
	fmt.Println(err)
	fmt.Println(string(jsonBytes))
}

What did you expect to see?

json.Marshal gives an error.

What did you see instead?

json.Marshal silently returns an empty json struct.

System details

go version go1.11.1 linux/amd64
GOARCH="amd64"
GOBIN=""
GOCACHE="/home/isaac/.cache/go-build"
GOEXE=""
GOFLAGS=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/isaac/go"
GOPROXY=""
GORACE=""
GOROOT="/usr/lib/go"
GOTMPDIR=""
GOTOOLDIR="/usr/lib/go/pkg/tool/linux_amd64"
GCCGO="gccgo"
CC="gcc"
CXX="g++"
CGO_ENABLED="1"
GOMOD=""
GOROOT/bin/go version: go version go1.11.1 linux/amd64
GOROOT/bin/go tool compile -V: compile version go1.11.1
uname -sr: Linux 4.18.14-arch1-1-ARCH
/usr/lib/libc.so.6: GNU C Library (GNU libc) stable release version 2.28.

@agnivade agnivade changed the title Duplicate struct tags cause json.Marshal to silently fail encoding/json: duplicate struct tags cause json.Marshal to silently fail Oct 20, 2018

@agnivade

This comment has been minimized.

Copy link
Member

commented Oct 20, 2018

FWIW, running it through vet does throw an error.

Paging @mvdan @dsnet for further comments.

@agnivade agnivade added this to the Unplanned milestone Oct 20, 2018

@mvdan

This comment has been minimized.

Copy link
Member

commented Oct 20, 2018

This is documented, so it cannot be changed - https://golang.org/pkg/encoding/json/:

  1. Otherwise there are multiple fields, and all are ignored; no error occurs.

The same issue has been raised before, too. See #17913 for example.

@mvdan mvdan closed this Oct 20, 2018

@is8ac

This comment has been minimized.

Copy link
Author

commented Oct 20, 2018

Thank you for your comments.
As you say, go vet would have alerted me to this issue. I shall be sure to use on my code it in future.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.