M.A*_*A.G 5 json http go unmarshalling
我想做的是将我从第三方 API 获得的 JSON 响应转换为字符串,以便能够在网页上呈现它。我首先尝试创建一个名为 的结构体money,其中包含要返回的 3 个值,然后Unmarshel是字节,但我没有显示任何内容
这是结构
type money struct {
Base string `json:"base"`
Currency string `json:"currency"`
Amount float32 `json:"amount"`}
Run Code Online (Sandbox Code Playgroud)
并在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)
}
Run Code Online (Sandbox Code Playgroud)
最后这是我从 json 响应中得到的结果
{"data":{"base":"BTC","currency":"USD","amount":"4225.87"}}
Run Code Online (Sandbox Code Playgroud)
Eve*_*ton 10
我必须从“金额”值中删除双引号,以便允许解析为 float32:
{"data":{"base":"BTC","currency":"USD","amount":4225.87}}
Run Code Online (Sandbox Code Playgroud)
请参阅 Playground: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)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
56120 次 |
| 最近记录: |