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 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改
  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效