doushang8846 2018-12-01 21:44
浏览 849

在golang中将Json转换为字符串

What I am trying to do is to convert the JSON response I got from a third party API to string to be able to render it on the webpage. My attempt first was to create a struct called money which holds the 3 values which are being returned and then Unmarshel the bytes but I don't get anything displayed

Here is the struct

type money struct {
Base     string  `json:"base"`
Currency string  `json:"currency"`
Amount   float32 `json:"amount"`}

and inside the getCurrency() func

    response, err := http.Get("https://api.coinbase.com/v2/prices/spot?currency=USD")

if err != nil {
    fmt.Printf("The http requst failed with error %s 
", err)
} else {
    answer, _ := ioutil.ReadAll(response.Body)
    response := money{}
    json.Unmarshal([]byte(answer), &response)
    fmt.Fprintln(w, response)
    fmt.Fprintln(w, response.Currency)


}

Finally here is what i get from the json response

 {"data":{"base":"BTC","currency":"USD","amount":"4225.87"}}
  • 写回答

1条回答 默认 最新

  • dqeq885710 2018-12-01 22:01
    关注

    I had to remove the double quotes from the 'amount' value in order to allow the parsing into float32:

     {"data":{"base":"BTC","currency":"USD","amount":4225.87}}
    

    See on Playground: https://play.golang.org/p/4QVclgjrtyi

    Full code:

    package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    type money struct {
        Base     string  `json:"base"`
        Currency string  `json:"currency"`
        Amount   float32 `json:"amount"`
    }
    
    type info struct {
        Data money
    }
    
    func main() {
        str := `{"data":{"base":"BTC","currency":"USD","amount":4225.87}}`
    
        var i info
    
        if err := json.Unmarshal([]byte(str), &i); err != nil {
            fmt.Println("ugh: ", err)
        }
    
        fmt.Println("info: ", i)
        fmt.Println("currency: ", i.Data.Currency)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器