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: incorrect handling of tagged anonymous fields #11408

mxk opened this issue Jun 25, 2015 · 2 comments

encoding/json: incorrect handling of tagged anonymous fields #11408

mxk opened this issue Jun 25, 2015 · 2 comments


Copy link

@mxk mxk commented Jun 25, 2015

go1.4.2 windows/amd64

The json package documentation says "an anonymous struct field with a name given in its JSON tag is treated as having that name, rather than being anonymous." I expected the same encoding of both structs in the example above. The same problem exists when unmarshaling values, which is how I bumped into this in the first place.

@ianlancetaylor ianlancetaylor added this to the Unplanned milestone Jul 11, 2015
Copy link

@nodirt nodirt commented Oct 14, 2015

This happens because time.Time implements json.Marshaler:

As a result, S1 "inherits" JSON marshalling of the embedded time.Time.

I assume you embed time.Time because you want to have all its methods in S1. An alternative to making time.Time a named field is to override MarshalJSON and UnmarshalJSON in S1:

func (s S1) MarshalJSON() ([]byte, error) {
  return json.Marshal(S2{s.Time, s.Value})

func (s S1) UnmarshalJSON(data []byte) error {
  var s2 S2
  err := json.Unmarshal(data, &s2)
  s.Time = s2.Time
  s.Value = s2.Value
  return err

It works

Copy link

@minux minux commented Oct 15, 2015

Working as intended.

@minux minux closed this Oct 15, 2015
@golang golang locked and limited conversation to collaborators Oct 17, 2016
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
None yet
Linked pull requests

Successfully merging a pull request may close this issue.

None yet
5 participants