json - 在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"}}
解决方案
我必须从“金额”值中删除双引号,以便解析成 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)
}
推荐阅读
- reactjs - 为什么在 Netlify 上部署 React App 时会出现此错误?
- python - 如何根据绘图的 y 值调整太阳图高度
- javascript - Google API 问题
- bayesian - 如何在 ulam 接口中将预测变量矩阵乘以参数向量(重新思考 R 包)
- javascript - 每次提出问题时为画布标签生成唯一的 id 或类?
- powershell - 如何比较两个字符串变量
- kubernetes - GKE 删除部署不会删除副本集
- android - 在 Flutter 项目上运行 Gradle 任务 'assembleDebug' 会导致错误
- alfresco - Alfresco 自定义角色
- ffmpeg - 以相等的时间/间隔从视频创建多个缩略图