从深度嵌套的JSON文件(WikipediaAPI)中提取值
这是我作为Go新手第一次尝试从WikipediaAPI使用Go structs生成的JSON文件中访问深度嵌套的值。通读所有关于用Go解包的线程并没有多大帮助 Json示例文件(从WikipediaAPI中提取) 我想访问从深度嵌套的JSON文件(WikipediaAPI)中提取值,json,go,wikipedia-api,Json,Go,Wikipedia Api,这是我作为Go新手第一次尝试从WikipediaAPI使用Go structs生成的JSON文件中访问深度嵌套的值。通读所有关于用Go解包的线程并没有多大帮助 Json示例文件(从WikipediaAPI中提取) 我想访问title和extract的值。使用jq,这是很平常的: $ jq '.query.pages[] | .title, .extract' wikipedia-api-output "Go (programming language)" "Go i
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."
我最近一次尝试围棋失败:
这将返回预期结果,但用于提取所需值的
pageid
(25039021)是由Wikipedia生成的,无法猜测。有没有办法通配符该值,或者我需要先提取该pageid
值,然后像上面的代码那样使用它?使用映射,特别是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"`
}
这里的工作示例(修复了问题代码中的一些拼写错误后):谢谢@Adrian。成功了。继续学习…如果您不喜欢定义这些自定义结构,您可能希望尝试以下方法:
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)
}
type Page struct {
Title string `json:"title"`
Extract string `json:"extract"`
}
type Wiki struct {
Query struct {
Pages map[string]Page `json:"pages"`
} `json:"query"`
}