Golang: 如何解析/反序列化/解码JSON数组API响应?

10

我正在尝试解析维基百科API(位于https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Smithsonian_Institution/daily/20160101/20170101),并将其转换为结构体数组,然后我将打印出查看计数。

然而,我尝试实现的代码在构建和运行时没有在终端中返回任何内容?

我无法成功的代码如下。

   type Post struct {
    Project string `json:"project"`
    Article string `json:"article"`
    Granularity string `json:"granularity"`
    Timestamp string `json:"timestamp"`
    Access string `json:"access"`
    Agent string `json:"agent"`
    Views int `json:"views"`
}

func main(){
    //The name of the wikipedia post
    postName := "Smithsonian_Institution"

    //The frequency of
    period := "daily"

    //When to start the selection
    startDate := "20160101"

    //When to end the selection
    endDate := "20170101"

    url := fmt.Sprintf("https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/%s/%s/%s/%s", postName, period, startDate, endDate)

    //Get from URL
    req, err := http.Get(url)
    if err != nil{
        return
    }
    defer req.Body.Close()

    var posts []Post

    body, err := ioutil.ReadAll(req.Body)
    if err != nil {
        panic(err.Error())
    }

    json.Unmarshal(body, &posts)

    // Loop over structs and display the respective views.
    for p := range posts {
        fmt.Printf("Views = %v", posts[p].Views)
        fmt.Println()
    }

}

如何最优地从 API 获取 JSON 响应,然后解析该数组为结构体数组,最后将其插入数据存储或相应地打印出来。

谢谢

2个回答

19

结构声明可以互相嵌套。

下面的结构应该可以从那个json中转换出来:

type resp struct {
    Items []struct {
        Project string `json:"project"`
        Article string `json:"article"`
        Granularity string `json:"granularity"`
        Timestamp string `json:"timestamp"`
        Access string `json:"access"`
        Agent string `json:"agent"`
        Views int `json:"views"`
    } `json:"items"`
}

我用json-to-go生成了这个,当与JSON API一起使用时,它是一个很好的时间节省器。


5
"json-to-go" 真的是个救命稻草,谢谢! - Ilker Mutlu

9
你的解决方案:
data := struct {
    Items []struct {
        Project string `json:"project"`
        Article string `json:"article"`
        Granularity string `json:"granularity"`
        Timestamp string `json:"timestamp"`
        Access string `json:"access"`
        Agent string `json:"agent"`
        Views int `json:"views"`
    } `json:"items"`
}{}

// you don't need to convert body to []byte, ReadAll returns []byte

err := json.Unmarshal(body, &data)
if err != nil { // don't forget handle errors
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接