Dealing with embedded structs
Fields of a struct type will be encoded as JSON objects. If there are embedded structs, then the encoder has two options: encode the embedded struct at the same level as the enclosing struct or as a new JSON object.
How to do it...
- Use JSON tags to name enclosing struct fields and the embedded struct fields:
type Enclosing struct { Field string `json:"field"` Embedded } type Embedded struct { Field string `json:"embeddedField"` }
- Use
json.Marshal
to encode the struct as a JSON object:enc := Enclosing{ Field: "enclosing", Embedded: Embedded{ Field: "embedded", }, } data, err = json.Marshal(enc) // {"field":"enclosing","embeddedField":"...