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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向