作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
这是我作为 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/
我是一名优秀的程序员,十分优秀!