我将尝试将我从第三方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"}}
json.Marshal
将其转换为字符串。 - Eugene Lisitskyfmt.Fprintln(w, string(answer))
正常将原始 JSON 发送到网页。我想做的是显示特定的值,比如货币,而不是整个 JSON。 - M.A.G