gpt4 book ai didi

json - 使用 "embedded"键将 JSON 解码为结构

转载 作者:数据小太阳 更新时间:2023-10-29 03:05:48 25 4
gpt4 key购买 nike

我有这个 JSON:

{
id : "12345",
videos: {
results: [
{
id: "533ec655c3a3685448000505",
key: "cYyx5DwWu0k"
}
]
}
}

我想将它解码为这个结构:

type Film struct {
ID int `json:"id"`
Videos []Video `json:"videos"`
}

type Video struct {
ID string `json:"id"`
Key string `json:"key"`
}

我的意思是,我想将 Videos 结构字段设为 videos.results 数组。

如果我这样做:

body := //retrieve json above
var film Film
json.Unmarshal(body, &film)

显然不起作用,因为它无法将 videos json 键解码到 Video 数组,因为 results 键。

我该怎么做?

最佳答案

您可以为 Film 定义一个解码器,为您“解包”嵌套的 JSON 结构。示例:

func (f *Film) UnmarshalJSON(b []byte) error {
internal := struct {
ID int `json:"id"`
Videos struct {
Results []Video `json:"results"`
} `json:"videos"`
}{}

if err := json.Unmarshal(b, &internal); err != nil {
return err
}
f.ID = internal.ID
f.Videos = internal.Videos.Results
return nil
}

https://play.golang.org/p/rEiKqLYB-1

关于json - 使用 "embedded"键将 JSON 解码为结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39319380/

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