加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 19:03:01 所属栏目:大数据 来源:网络整理
导读:我正在尝试解析维基百科API的响应,该API位于https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Smithsonian_Institution/daily/ 20160101/20170101进入一个结构数组,我将继续打印出视图计数 但是,为
我正在尝试解析维基百科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
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读