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条)

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀