douhao2548 2017-04-26 03:18
浏览 100
已采纳

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

I am trying to parse the response from Wikipedia's API located at https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Smithsonian_Institution/daily/20160101/20170101 into an array of structs of which I will proceed to print out the view count

However, the code that I have tried to implement in order to achieve this returns nothing in the terminal when I build and run it?

The code I am failing to succeed with is as follows.

   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()
    }

}

What is the optimal method of receiving a json response from a API such as the one mentioned above and thereafter parsing that array into an array of structs, which can then be inserted into a datastore or printed out accordingly.

Thanks

  • 写回答

2条回答 默认 最新

  • dongpang2483 2017-04-26 03:59
    关注

    Your solution:

    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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!