How to get JSON response from http.Get

后端 未结 4 993
别那么骄傲
别那么骄傲 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条回答
  •  日久生厌
    2020-11-29 15:42

    The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

    package main
    
    import (
        "encoding/json"
        "fmt"
        "io/ioutil"
        "net/http"
        "os"
    )
    
    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"
        url += "&limit=1" // limit data for testing
        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 interface{} // TopTracks
        err = json.Unmarshal(body, &data)
        if err != nil {
            panic(err.Error())
        }
        fmt.Printf("Results: %v\n", data)
        os.Exit(0)
    }
    
    func main() {
        get_content()
    }
    

    Output:

    Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]
    

提交回复
热议问题