Marshal of nested structures in JSON

How to create a nested structure marker in JSON? I know how to marshal a structure without any nested structures. However, when I try to make the JSON response look like this:

{"genre": {"country": "taylor swift", "rock": "aimee"}} 

I'm having problems.

My code is as follows:

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 an error

Missing type in composite literal

How to resolve this?

+8
go marshalling
source share
3 answers

Here is a 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 repetition, I recommend defining the type for the genre. In addition, use field tags to indicate lowercase 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

+13
source share

Use JsonUtils. This is a program that generates Go structures from a json file:
https://github.com/bashtian/jsonutils

+2
source share

Why not set the json parameter for struct values? https://play.golang.org/p/n6aJdQgfom

+1
source share

All Articles