首页 > 解决方案 > 在golang中将Json转换为字符串

问题描述

我想要做的是将我从第三方 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"}}

标签: jsonhttpgounmarshalling

解决方案


我必须从“金额”值中删除双引号,以便解析成 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)
}

推荐阅读