Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Marshal nested structs into JSON

Tags:

go

marshalling

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?

like image 575
user3918985 Avatar asked Dec 28 '14 13:12

user3918985


2 Answers

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

like image 162
Bayta Darell Avatar answered Nov 18 '22 19:11

Bayta Darell


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

like image 28
Karl Avatar answered Nov 18 '22 18:11

Karl