4

如果给定字符串,来自 MediaWiki API 请求:

str = ` {
    "query": {
        "pages": {
            "66984": {
                "pageid": 66984,
                "ns": 0,
                "title": "Main Page",
                "touched": "2012-11-23T06:44:22Z",
                "lastrevid": 1347044,
                "counter": "",
                "length": 28,
                "redirect": "",
                "starttimestamp": "2012-12-15T05:21:21Z",
                "edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\"
            }
        }
    }
}`

使用Go 的 json 包可以做些什么来获取 edittoken (请记住 66984 数字会不断变化)?

4

2 回答 2

5

当您有这样的更改键时,处理它的最佳方法是使用地图。在下面的示例中,我一直使用结构,直到我们到达更改键为止。之后我切换到地图格式。我也链接了一个工作示例。

http://play.golang.org/p/ny0kyafgYO

package main

import (
    "fmt"
    "encoding/json"
    )

type query struct {
    Query struct {
        Pages map[string]interface{}
    }
}


func main() {
    str := `{"query":{"pages":{"66984":{"pageid":66984,"ns":0,"title":"Main Page","touched":"2012-11-23T06:44:22Z","lastrevid":1347044,"counter":"","length":28,"redirect":"","starttimestamp":"2012-12-15T05:21:21Z","edittoken":"bd7d4a61cc4ce6489e68c21259e6e416+\\"}}}}`

    q := query{}
    err := json.Unmarshal([]byte(str), &q)
    if err!=nil {
        panic(err)
    }
    for _, p := range q.Query.Pages {
        fmt.Printf("edittoken = %s\n", p.(map[string]interface{})["edittoken"].(string))
    }
}
于 2012-12-15T06:17:31.747 回答
4

请注意,如果您&indexpageids=true在 API 请求 URL 中使用参数,则结果将包含一个“pageids”数组,如下所示:

str = ` {
    "query": {
        "pageids": [
            "66984"
        ],
        "pages": {
            "66984": {
                "pageid": 66984,
                "ns": 0,
                "title": "Main Page",
                "touched": "2012-11-23T06:44:22Z",
                "lastrevid": 1347044,
                "counter": "",
                "length": 28,
                "redirect": "",
                "starttimestamp": "2012-12-15T05:21:21Z",
                "edittoken": "bd7d4a61cc4ce6489e68c21259e6e416+\\"
            }
        }
    }
}`

因此您可以使用它pageids[0]来访问不断变化的数字,这可能会使事情变得更容易。

于 2012-12-15T12:59:09.173 回答