我主要是在python中编程,我正在教自己一些Go!
我试图解析api调用中的JSON数据时遇到了绊脚石,我现在转向这个伟大的社区寻求建议!我在网上找不到的任何东西都有效,所以任何建议,即使它只是与其余的代码相关,都会有所帮助!
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
)
//Time blah
type Time struct {
Updated string `json:"updated"`
UpdatedISO string `json:"updatedISO"`
Updateduk string `json:"updateduk"`
}
//Currency blah blah
type Currency struct {
Code string `json:"code"`
Rate float64 `json:"rate"`
Descr string `json:"description"`
Rf float64 `json:"rate-float"`
}
//Bpi blah
type Bpi struct {
Usd []Currency `json:"USD"`
Eur []Currency `json:"EUR"`
}
//ListResponse is a blah
type ListResponse struct {
Time []Time `json:"time"`
Disclaimer string `json:"disclaimer"`
Bpi []Bpi `json:"bpi"`
}
func btcPrice() {
url := "https://api.coindesk.com/v1/bpi/currentprice/eur.json"
req, err := http.Get(url)
if err != nil {
panic(err.Error())
} else {
data, err := ioutil.ReadAll(req.Body)
if err != nil {
fmt.Println("Error at the data stage: ", err)
}
// fmt.Println(string(data))
var result ListResponse
json.Unmarshal(data, &result)
fmt.Println(result)
}
}
func main() {
btcPrice()
}
Run Code Online (Sandbox Code Playgroud)
基本上上面的代码是进行api调用,获取JSON数据并使用上面的结构操作它.(我可能会以错误的方式完成这个问题,所以如果是这样,请致电我).
这里有些事情让我感到沮丧.返回的JSON如下:
{
"time":{
"updated":"Dec 10, 2017 20:41:00 UTC",
"updatedISO":"2017-12-10T20:41:00+00:00",
"updateduk":"Dec 10, 2017 at 20:41 GMT"
},
"disclaimer":"This data was produced from the CoinDesk Bitcoin Price Index (USD). Non-USD currency data converted using hourly conversion rate from openexchangerates.org",
"bpi":{
"USD":{
"code":"USD",
"rate":"15,453.3888",
"description":"United States Dollar",
"rate_float":15453.3888
},
"EUR":{
"code":"EUR",
"rate":"13,134.4532",
"description":"Euro",
"rate_float":13134.4532
}
}
}
Run Code Online (Sandbox Code Playgroud)
我想要做的是单独访问json数据集,但问题似乎在我的结构中.如果我调用一个基本的打印(在上面的代码中注释,你可以看到),json的整个数据集打印.但是当我使用结果代码和json.unmarshal它只给我免责声明,即部分struct简单地标记为string类型.
如果他们在评论中受到质疑,我可能似乎在漫无边际地澄清陈述.
总结一下:
你的结构有问题.如果你看到jsonapi调用返回的,则没有time和bpikey的数组值,所有这些都是对象.同样适用USD和EUR关键.
还有两个错别字/错误:
rate字符串不浮动.(你必须在将其作为字符串读取后转换为float)rate-float 应该 rate_float这是完整的工作(为我工作):
//Currency blah blah
type Currency struct {
Code string `json:"code"`
Rate string `json:"rate"`
Descr string `json:"description"`
Rf float64 `json:"rate_float"`
}
//Bpi blah
type Bpi struct {
Usd Currency `json:"USD"`
Eur Currency `json:"EUR"`
}
//ListResponse is a blah
type ListResponse struct {
Time Time `json:"time"`
Disclaimer string `json:"disclaimer"`
Bpi Bpi `json:"bpi"`
}
Run Code Online (Sandbox Code Playgroud)
与你交叉检查.希望能帮助到你!