Skip to content

encoding/json: multiple anonymous struct fields shouldn't be ignored #11006

@themihai

Description

@themihai

Currently if there are duplicate anonymous struct fields they are all ignored. I think this is wrong because the encoding process shouldn't loose information unless the output format is not capable to represent it(which is not the case).
For example marshalling AllTypes produces an empty output.
type AllTypes struct {
Type1
Type2
}
type Type1 struct {
Name string
Address string
}
type Type2 struct {
Name string
Address string
}
To overcome this issue an additional step is required to create a boilerplate type specially for the encoding/decoding process. Most likely we end-up with a new type (AllTypes2) as below. This is against the composability of the language and adds additional burden to the developer(look for duplicate fields -> create a new type).

type AllTypes2 struct{
Type1 Type1
Type2 Type2
}

Any fix/convention that preserves the data would be fine to me but I present my proposal below too as starting point. I think it's also backward compatible.
Use the same addressing like the native go types.
If there are duplicate anonymous fields, they should be addressed using the type name as prefix. If the type name is duplicate too both the package name and the type name should be used as prefix. For type AllTypes I would expect the output below:

{
"Type1": {"Name":"example", "Address": "example"},
"Type2": {"Name":"example", "Address": "example"}
}

Using the same addressing as on go types makes the behaviour intuitive and easier to understand too as we have only one familiar rule instead of 3 special rules.
It would make the behaviour more consistent too because the type name is already used as key on certain cases. For example type SomeType is encoded to {"MySlice":["somedata"]}.
type SomeType struct{
MySlice
}
type MySlice []string

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions