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.Marshalto encode the struct as a JSON object:enc := Enclosing{ Â Â Â Â Â Field: "enclosing", Â Â Â Â Â Embedded: Embedded{ Â Â Â Â Â Â Â Â Â Â Field: "embedded", Â Â Â Â Â }, } data, err = json.Marshal(enc) // {"field":"enclosing","embeddedField":"...