Golang: How to parse / decouple / decode json array API response?

I am trying to analyze the response of the Wikipedia API located in https://wikimedia.org/api/rest_v1/metrics/pageviews/per-article/en.wikipedia.org/all-access/all-agents/Smithsonian_Institution/daily/20160101/20170101to an array of structures from which I will proceed to print out the number of views

However, the code that I tried to implement to achieve this does not return anything to the terminal when I create and run it?

The code that I am unable to execute 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 best way to get a json response from an API like the one mentioned above, and then parse this array into an array of structures that can then be inserted into the data store or printed accordingly.

thanks

+6
2

:

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
}
+3

.

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, API- JSON.

+2

Source: https://habr.com/ru/post/1016780/


All Articles