gpt4 book ai didi

arrays - 如何在 golang 中给 Json 数组一个标识符

转载 作者:IT王子 更新时间:2023-10-29 02:33:05 25 4
gpt4 key购买 nike

我正在尝试使用 json.Marshall 在 Go 中创建一个带有结构的 JSON 数组,但是我似乎无法在这里获得所需的结果是我正在使用的结构 slice 。

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

我正试图将它编码成一个看起来像这样的结构

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

但是我卡在了

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

我不知道如何获取 json 数组周围的附加 {"posts":..}。如何将此附加标识符添加到 json 数组?谢谢

最佳答案

用结构包裹 slice 以添加带有“posts”字段的 JSON 对象:

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

另一种方法是用 map 包裹 slice :

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

关于arrays - 如何在 golang 中给 Json 数组一个标识符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39977034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com