从深度嵌套的JSON文件(Wikipedia API)中提取价值

时间:2020-09-25 15:44:58

标签: json go wikipedia-api

作为Go newbee,这是我第一次尝试使用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."
      }
    }
  }
}

我想访问titleextract的值。使用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值,然后像上面的代码一样使用它?

1 个答案:

答案 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