gpt4 book ai didi

json - Golang,将 json 解码为自定义结构

转载 作者:IT王子 更新时间:2023-10-29 01:55:52 24 4
gpt4 key购买 nike

我正在尝试将 reddit 内容从 json API 提取到客户端的自定义结构中。我为此想出的结构是

type Subreddit struct {
offset int
num_of_posts int
subscribers: int
thumbnail string
children []post
}

type post struct {
type string
url string
thumbnail string
submitted_by string
upvotes int
downvotes int
}

不幸的是,reddit json 的格式甚至没有接近这个,此外我想过滤掉我不支持的 url 等。

我知道这样做的唯一方法是为源数据中的每个“ child ”创建一个界面,并手动遍历每个 child ,为每个界面创建一个单独的“帖子”。并将它们推送到 subreddit 对象的 post 数组中。

作为引用,数据的格式类似于 http://www.reddit.com/r/web_design/.json

这样做正确吗?或者有没有更快的方法。对于这么小的任务来说似乎有很多开销,但我是一名 PHP Javascript 开发人员,所以我想这对我来说很不寻常。

最佳答案

在我开始回答问题之前:
请记住,您的结构字段必须导出才能与encoding/json 包一起使用。

其次,我必须承认我不完全确定您对整个 create an interface for each of the "children" 部分的意思。但这听起来很复杂 ;)
不管怎样,对你的回答:

如果您希望使用标准的 encoding/json 包来解码 json,您必须使用中间结构,除非您将使用与 Reddit 使用的结构类似的结构。

您可以在下面找到一个示例,说明 Reddit 结构的某些部分如何映射到 Go 结构。通过将 json 解码到 RedditRoot 的一个实例中,您可以轻松地遍历 Children ,删除任何不需要的 child ,并填充您的 Subreddit 结构:

type RedditRoot struct {
Kind string `json:"kind"`
Data RedditData `json:"data"`
}

type RedditData struct {
Children []RedditDataChild `json:"children"`
}

type RedditDataChild struct {
Kind string `json:"kind"`
Data *Post `json:"data"`
}

type Post struct {
Type string `json:"-"` // Is this equal to data.children[].data.kind?
Url string `json:"url"`
Thumbnail string `json:"thumbnail"`
Submitted_by string `json:"author"`
Upvotes int `json:"ups"`
Downvotes int `json:"downs"`
}

关于json - Golang,将 json 解码为自定义结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20866817/

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