在golang中将Json转换为字符串

时间:2018-12-01 21:44:36

标签: json http go unmarshalling

我想做的是将我从第三方API获得的JSON响应转换为字符串,以便能够在网页上呈现它。我首先尝试创建一个名为money的结构,该结构包含要返回的3个值,然后Unmarshel个字节,但没有显示任何内容

这是结构

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

并在getCurrency()函数内

    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 \n", err)
} else {
    answer, _ := ioutil.ReadAll(response.Body)
    response := money{}
    json.Unmarshal([]byte(answer), &response)
    fmt.Fprintln(w, response)
    fmt.Fprintln(w, response.Currency)


}

最后这就是我从json响应中得到的结果

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

1 个答案:

答案 0 :(得分:2)

我必须从“金额”值中删除双引号,以便允许将其解析为float32:

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

在操场上观看:https://play.golang.org/p/4QVclgjrtyi

完整代码:

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