How to get JSON response from http.Get

后端 未结 4 996
别那么骄傲
别那么骄傲 2020-11-29 15:22

I\'m trying read JSON data from web, but that code returns empty result. I\'m not sure what I\'m doing wrong here.

package main

import \"os\"
import \"fmt\"         


        
4条回答
  •  旧时难觅i
    2020-11-29 15:40

    You need upper case property names in your structs in order to be used by the json packages.

    Upper case property names are exported properties. Lower case property names are not exported.

    You also need to pass the your data object by reference (&data).

    package main
    
    import "os"
    import "fmt"
    import "net/http"
    import "io/ioutil"
    import "encoding/json"
    
    type tracks struct {
        Toptracks []toptracks_info
    }
    
    type toptracks_info struct {
        Track []track_info
        Attr  []attr_info
    }
    
    type track_info struct {
        Name       string
        Duration   string
        Listeners  string
        Mbid       string
        Url        string
        Streamable []streamable_info
        Artist     []artist_info
        Attr       []track_attr_info
    }
    
    type attr_info struct {
        Country    string
        Page       string
        PerPage    string
        TotalPages string
        Total      string
    }
    
    type streamable_info struct {
        Text      string
        Fulltrack string
    }
    
    type artist_info struct {
        Name string
        Mbid string
        Url  string
    }
    
    type track_attr_info struct {
        Rank string
    }
    
    func get_content() {
        // json data
        url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    
        res, err := http.Get(url)
    
        if err != nil {
            panic(err.Error())
        }
    
        body, err := ioutil.ReadAll(res.Body)
    
        if err != nil {
            panic(err.Error())
        }
    
        var data tracks
        json.Unmarshal(body, &data)
        fmt.Printf("Results: %v\n", data)
        os.Exit(0)
    }
    
    func main() {
        get_content()
    }
    

提交回复
热议问题