Golang Struct Won't Marshal to JSON -
this question has answer here:
- my structures not marshalling json 2 answers
i'm trying marshal struct in go json won't marshal , can't understand why.
my struct definitions
type podscondensed struct { pods []podcondensed `json:"pods"` } func (p *podscondensed) addpod(pod podcondensed) { p.pods = append(p.pods, pod) } type podcondensed struct { name string `json:"name"` colors []string `json:"colors"` } creating , marshaling test struct
fake_pods := podscondensed{} fake_pod := podcondensed { name: "tier2", colors: []string{"blue", "green"}, } fake_pods.addpod(fake_pod) fmt.println(fake_pods.pods) jpods, _ := json.marshal(fake_pods) fmt.println(string(jpods)) output
[{tier2 [blue green]}] {} i'm not sure issue here, export json data structs, data being stored correctly , available print. wont marshal odd because contained in struct can marshaled json on own.
this common mistake: did not export values in podscondensed , podcondensed structures, json package not able use it. use capital letter in variable name so:
type podscondensed struct { pods []podcondensed `json:"pods"` } type podcondensed struct { name string `json:"name"` colors []string `json:"colors"` } - working example: http://play.golang.org/p/lg3cto7dvk
- documentation: http://golang.org/pkg/encoding/json/#marshal
Comments
Post a Comment