dongtao9158 2018-04-24 08:16
浏览 44
已采纳

如何解决此程序中打印出的JSON数据?

I am trying to convert data through api url into JSON data. As a whole it works, but when I want to get specific data set from JSON (here I am trying MyStruct which is a data set having name, duration, listners), so it comes with blank result. On the other side, same problem with html template which does not give any result when I call it through local host port. I have declared a global instance to call data set in template function (could also use in my get content function though) but having fail result. I am wondered why data variable in get_content having blank result?

// created structurs example
type MyStruct struct {
    Name       string
    Duration   string
    and so on..
}
var data1 MyStruct

// function to retreive api data & convert into json.
func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "" // 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 MyStruct
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v
", data)
}

func main() {
    http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
        get_content()
    })

    http.HandleFunc("/", template1)
    http.ListenAndServe(":8080", nil)

}

func template1(w http.ResponseWriter, r *http.Request) {

    fp := path.Join("index.html")
    tmpl, err := template.ParseFiles(fp)
    if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
    }

    if err := tmpl.Execute(w, data1); err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
    }
}

on index file I have written names to call the data:

{{.Name}}
{{.Duration}}
{{.Listeners}}
  • 写回答

1条回答 默认 最新

  • doqvzh345334 2018-04-24 09:21
    关注

    To be a bit more explicit, the go data structure must match the json data structure. Not just the individual 'track', but the entire json structure.

    Here's an example based on the response from the url you gave. The response is reduced to fit here, the full response is on the Playground.

    The names returned by the json structure are misleading, but it's workable.

    package main
    
    import (
        "encoding/json"
        "fmt"
        "log"
    )
    
    type Track struct {
        Name     string `json:"name"`
        Duration string `json:"duration"`
        //... etc
    }
    
    type Data struct {
        Content struct {
            Tracks []Track `json:"track"`
        } `json:"tracks"`
    }
    
    func main() {
        var body = []byte(`{
            "tracks":{
                "track":[
                    {
                        "name":"Hello",
                        "duration":"123",
                        "listeners":"373721",
                        "mbid":""
                    }
                ]
            }
        }`)
    
        var data Data
        err := json.Unmarshal(body, &data)
        if err != nil {
            log.Fatal(err)
        }
    
        for _, track := range data.Content.Tracks {
            fmt.Printf("Track: %s
    ", track.Name)
        }
    }
    

    Replacing body with the full json (eg, from the url response) and running this prints:

    Track: Hello Track: Can't Feel My Face Track: Sultans of Swing Track: Sorry Track: Lean On (feat. MØ & DJ Snake) Track: The Less I Know the Better Track: Africa ...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?