JSON decoding and union types

366 views
Skip to first unread message

Dustin

unread,
Dec 28, 2011, 12:18:05 AM12/28/11
to golan...@googlegroups.com
Is it wrong to expect this to work?

package main

import (
"encoding/json"
"fmt"
)

type Base struct {
Label string `json:"lbl"`
}

type Sub struct {
Base

OtherField string `json:"field"`
}

func main() {
s := Sub{}

json.Unmarshal([]byte(`{"lbl": "A Label", "field": "A Field"}`), &s)

fmt.Printf("Label:\t%v\nField:\t%v\n", s.Label, s.OtherField)
}

That is, the composition doesn't create a "flat" structure and the JSON unmarshaller can't find the base fields although they're there as far as the language itself is concerned (%#v of s is `main.Sub{Base:main.Base{Label:""}, OtherField:"A Field"}`)

Evan Shaw

unread,
Dec 28, 2011, 12:24:52 AM12/28/11
to golan...@googlegroups.com

This has been a recent topic of discussion on the dev list. I
submitted a CL to try and fix it but there are complications. See:
http://codereview.appspot.com/5233053/ (for some reason only part of
the thread shows up on groups.google.com)

I agree with the way you think json should work and the developers
seem to also, but there are other more pressing issues.

- Evan

Dustin

unread,
Dec 28, 2011, 12:42:50 AM12/28/11
to golan...@googlegroups.com
Excellent.  This isn't a pressing issue for me now, either.  The thing I was attempting to implement expressed itself in terms of a hierarchy of JSON types, which didn't work, but I figured out along the way that this is a gigantic read only interface, so I mostly lost interest.

I am looking forward to your change, though.
Reply all
Reply to author
Forward
0 new messages