arrays - 戈朗 :How to parse/unmarshal/decode a json array API response?

标签 arrays json go unmarshalling decoding

我正在尝试解析位于 https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all- 的维基百科 API 的响应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 响应的最佳方法是什么,然后将该数组解析为结构数组,然后可以将其插入数据存储或相应地打印出来。

谢谢

最佳答案

结构声明可以相互嵌套。

以下结构应该可以从该 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"`
}

我用 json-to-go 生成的,这在使用 JSON API 时非常节省时间。

关于arrays - 戈朗 :How to parse/unmarshal/decode a json array API response?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43624404/

相关文章:

python - 将大量数据存储到 numpy 数组中

java - 给定一个字符串数组,单词,返回该数组,并将所有偶数长度的字符串替换为空字符串

javascript - 如何更改订单键和值数组

c# - 如何使用 WebClient.UploadString 方法下载图片?

go - 无法安装 Go 软件包

go - 初始化嵌套匿名结构

javascript - 使用剩余参数将参数展平为一维数组

php - 如何从 codeigniter Controller 传递多个 json 变量以在 ajax 中查看。

javascript - 如何禁用 d3 折线图中 x 轴的数据排序?

html - zserge/lorca HTML 提交到 go func