gpt4 book ai didi

json - 从深度嵌套的 JSON 文件中提取值(维基百科 API)

转载 作者:行者123 更新时间:2023-12-01 22:38:59 26 4
gpt4 key购买 nike

这是我作为 Go 新手的第一次尝试,从使用 Go 结构的 Wikipedia API 生成的 JSON 文件中访问深度嵌套的值。通读所有关于用 Go 解码的线程并没有多大帮助。
Json 示例文件(从 Wikipedia API 中提取)

{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "Go_(programming_language)",
"to": "Go (programming language)"
}
],
"pages": {
"25039021": {
"pageid": 25039021,
"ns": 0,
"title": "Go (programming language)",
"extract": "Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson."
}
}
}
}
我想访问 title 的值和 extract .使用 jq 很简单:
$ jq '.query.pages[] | .title, .extract' wikipedia-api-output
"Go (programming language)"
"Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson."
我最近一次失败的尝试:
type Wiki struct {
Query struct {
Pages struct {
Article struct {
Title string `json:"title`
Extract string `json:"extract`
} `json:"25039021"`
} `json:"pages"`
} `json:"query"`
}

func main() {

jsonStr :=
`{
"batchcomplete": "",
"query": {
"normalized": [
{
"from": "Go_(programming_language)",
"to": "Go (programming language)"
}
],
"pages": {
"25039021": {
"pageid": 25039021,
"ns": 0,
"title": "Go (programming language)",
"extract": "Go is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson."
}
}
}
}`
var wikiDescr Wiki
err := json.Unmarshal([]byte(jsonStr), &wikiDescr)
if err != nil {
fmt.Println(err)
}

fmt.Println(wikiDescr)

}
这将返回预期结果,但 pageid (25039021) 用于提取所需值是由维基百科生成的,无法猜测。有没有办法给这个值加上通配符或者我需要提取那个 pageid先取值,然后像上面的代码一样使用它?

最佳答案

使用 map ,特别是 map[string]Page在哪里 Page是您的页面数据结构:

type Page struct {
Title string `json:"title"`
Extract string `json:"extract"`
}

type Wiki struct {
Query struct {
Pages map[string]Page `json:"pages"`
} `json:"query"`
}
此处的工作示例(在修复问题代码中的一些错别字之后): https://play.golang.org/p/z9Ngcae9O1F

关于json - 从深度嵌套的 JSON 文件中提取值(维基百科 API),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64067354/

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