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

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
    }
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • dongyouzhui1969 2017-04-26 03:53

    Struct declarations can be nested inside one another.

    The following struct should be convertable from that 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"`
    }
    

    I generated that with json-to-go, which is a great time saver when working with JSON APIs.

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题