gomarshalling

Marshal nested structs into JSON


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?


Solution

  • 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