[英]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. 我正在尝试使用json.Marshall
在带有结构的Go中创建一个JSON数组,但是我似乎无法获得所需的结果,这是我正在使用的结构片。
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. 我不知道如何在json数组周围获取其他{"posts":..}
。 How do I add this additional identifier to the json array? 如何将此附加标识符添加到json数组? Thanks 谢谢
Wrap the slice with a struct to add the JSON object with "posts" field: 用结构包裹切片,以使用“ posts”字段添加JSON对象:
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})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.