数组 – Golang:如何解析/解组/解码json数组API响应?

前端之家收集整理的这篇文章主要介绍了数组 – Golang:如何解析/解组/解码json数组API响应?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在尝试解析维基百科API的响应,该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(例如上面提到的API)接收json响应的最佳方法,然后将该数组解析为结构数组,然后可以将其插入数据存储区或相应地打印出来.

谢谢

你的解决方
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
}
原文链接:https://www.f2er.com/go/242056.html

猜你在找的Go相关文章