Colleen Larsen Colleen Larsen - 1 month ago 7
JSON Question

How to give a Json array an Identifier in golang

I am trying to create a JSON array in Go with a struct using

json.Marshall
however I cant seem to get the desired result here is the slice of structs I am working with.

posts := []models.Post{
models.Post{Id: 1,MediaUrl:"...", Title: "...", Slug: "...", ShortDescription : "...", Content : "..."},
models.Post{Id: 2,MediaUrl:"...", Title: "...", Slug: "...", ShortDescription : "...", Content : "..."},
}


And I am trying to marshall it into a struct that looks like

{"posts":[{"Id": 1,...},{"Id": 2,...}]}


But I am stuck at

[{"Id":1,...},{"Id": 2,...}]


I dont know how to get the additional
{"posts":..}
around the json array.
How do I add this additional identifier to the json array?
Thanks

Answer

Wrap the slice with a struct to add the JSON object with "posts" field:

data := struct { 
   Posts []models.Post `json:"posts"`
}{
   Posts: posts
}
p, err := json.Marshal(&data)

An alternative is to wrap the slice with a map:

p, err := json.Marshal(map[string]interface{}{"posts": posts})