How do I marshal a nested struct into JSON? I know how to marshal the struct without any nested structs. However when I try to make the JSON response look like this:
{"genre": {"country": "taylor swift", "rock": "aimee"}}
I run into problems.
My code looks like this:
Go:
type Music struct {
Genre struct {
Country string
Rock string
}
}
resp := Music{
Genre: { // error on this line.
Country: "Taylor Swift",
Rock: "Aimee",
},
}
js, _ := json.Marshal(resp)
w.Write(js)
However, I get the error
Missing type in composite literal
How do I resolve this?
Here's the composite literal for your type:
resp := Music{
Genre: struct {
Country string
Rock string
}{
Country: "Taylor Swift",
Rock: "Aimee",
},
}
playground example
You need to repeat the anonymous type in the literal. To avoid the repetition, I recommend defining a type for Genre. Also, use field tags to specify lowercase key names in the output.
type Genre struct {
Country string `json:"country"`
Rock string `json:"rock"`
}
type Music struct {
Genre Genre `json:"genre"`
}
resp := Music{
Genre{
Country: "Taylor Swift",
Rock: "Aimee",
},
}
playground example
Use JsonUtils. It is a program that generates Go structures from a json file:
https://github.com/bashtian/jsonutils
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With