作为Go newbee,这是我第一次尝试使用Go结构从Wikipedia API生成的JSON文件访问深度嵌套的值。仔细阅读所有有关使用Go进行编组的主题并没有多大帮助。
{
"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)由Wikipedia生成,无法猜测。是否可以通配该值,还是需要先提取该pageid
值,然后像上面的代码一样使用它?
答案 0 :(得分:2)
使用地图,尤其是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