JSON encoding of anonymous fields

243 views
Skip to first unread message

David Campbell

unread,
Jun 30, 2012, 3:13:51 PM6/30/12
to golan...@googlegroups.com
A couple of days ago I discussed on IRC a few different ways to handle
the encoding of anonymous fields embedded in structs into JSON (issue
3069). The idea is to encode the fields of an anonymous struct as
though they were outside of the anonymous struct, similarly to what is
done in the xml package. The issue is what to do when two anonymous
structs have fields with the same name.

type A struct {
Foo string
int
Bar int
}

type B struct {
Foo string
int
Baz int
}

type C struct {
A
B
}

Solutions:
1. Return an error.
2. If two fields collide, overwrite the field with whichever field is
read later.
{"Foo": "", "int": 0, "Bar": 0, "Baz": 0}
3. Leave out the colliding fields altogether, possibly also doing 1.
{"Bar": 0, "Baz": 0}
4. If there are colliding fields, don't inline those:
{"A":{"Foo": "", "int": 0}, "B":{"foo": "", "int": 0},"Bar": 0, "Baz": 0}

My feeling is that 4 is the best solution since it mirrors how one
would access the fields of the struct in Go: C.A.Foo, C.Baz, but 2
would provide for the simplest implementation. I don't like the idea
of leaving out colliding fields, and I don't think an error makes
sense since the struct is a valid struct and this could also break
existing code. I would appreciate the feedback of others on what the
best approach is here and to know whether a patch taking the 4th
approach would be welcome.

--
David Campbell

Kyle Lemons

unread,
Jul 1, 2012, 12:01:23 AM7/1/12
to David Campbell, golan...@googlegroups.com
On Sat, Jun 30, 2012 at 12:13 PM, David Campbell <dcamp...@gmail.com> wrote:
A couple of days ago I discussed on IRC a few different ways to handle
the encoding of anonymous fields embedded in structs into JSON (issue
3069). The idea is to encode the fields of an anonymous struct as
though they were outside of the anonymous struct, similarly to what is
done in the xml package.The issue is what to do when two anonymous

I think that the best thing to do is #1, because that's consistent with what XML does.  I would somewhat prefer 3, though I have a feeling that if I thought about it more I'd fall back to #1.  The #4 seems nice up front, but I think it has the problem that if you embed a struct that grows a new (duplicate) field, it could cause silent failures on the encoding side.
Reply all
Reply to author
Forward
0 new messages