发现去json解码是一个很大的痛苦,所以请帮忙。 这是我的json:
{
"BTC_BCN":{
"id":7,
"last":"0.00000156",
"lowestAsk":"0.00000156",
"highestBid":"0.00000155",
"percentChange":"0.01960784",
"baseVolume":"4920.84786257",
"quoteVolume":"3016048494.19305944",
"isFrozen":"0",
"high24hr":"0.00000183",
"low24hr":"0.00000145"
},
"BTC_BELA":{
"id":8,
"last":"0.00008847",
"lowestAsk":"0.00008848",
"highestBid":"0.00008847",
"percentChange":"-0.00405268",
"baseVolume":"169.66498061",
"quoteVolume":"1981232.44495809",
"isFrozen":"0",
"high24hr":"0.00008995",
"low24hr":"0.00008120"
}, ...
}
所以我需要把它放在我创建的类型中
//Crypto is the currency object
type Crypto struct {
iso string //this is the key (ex: BTC_BCN)
id int
last float64
lowestAsk float64
highestBid float64
percentChange float64
baseVolume float64
quoteVolume float64
isFrozen int
high24hr float64
low24hr float64
}
这是我到目前为止所做的,但我最终得到了键和空值
func main() {
// sendEmail("Some text")
currencies := getCurrencies()
if currencies == nil {
return
}
fmt.Println(len(currencies))
}
func getCurrencies() map[string]Crypto {
curList := make(map[string]Crypto)
resp, err := http.Get("https://poloniex.com/public?command=returnTicker")
// fmt.Println(err)
if err != nil {
sendEmail("Error getting data from poloniex " + err.Error())
return nil
}
body, readErr := ioutil.ReadAll(resp.Body)
reader := strings.NewReader(string(body))
jsonErr := json.NewDecoder(reader).Decode(&curList)
// fmt.Printf("curList is : %#v\n", curList)
// fmt.Printf("body is : %s\n", string(body))
if readErr != nil {
fmt.Printf("readErr: %s\n", readErr.Error())
}
if jsonErr != nil {
fmt.Printf("jsonErr: %s\n", jsonErr.Error())
}
for k, v := range curList {
fmt.Println("k:", k, "v:", v)
}
defer resp.Body.Close()
return curList
}
输出:
k: BTC_MAID v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_NOTE v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_VRC v: {0 0 0 0 0 0 0 0 0 0}
k: BTC_DOGE v: {0 0 0 0 0 0 0 0 0 0}...
请原谅我的愚蠢问题,但我花了好几天时间,我想我错过了一些东西。 欢呼声。
答案 0 :(得分:2)
//Crypto is the currency object
type Crypto struct {
Iso string //this is the key (ex: BTC_BCN)
Id int
Last string
LowestAsk string
HighestBid string
PercentChange string
BaseVolume string
QuoteVolume string
IsFrozen int
High24hr string
Low24hr string
}
您需要通过大写第一个字符来导出字段。最重要的是,您的float64
数据类型为string
,因此您可以在分配给对象Crypto
之前将其读作字符串或格式。
<强>更新强>
正如@skomp所指出的,您可以使用标记来注释您从json文件接收的类型。
type Crypto struct {
CryptoKey
Id int
Last float64 `json:"last,string"`
LowestAsk float64 `json:"lowestAsk,string"`
HighestBid float64 `json:"highestBid,string"`
PercentChange float64 `json:"percentChange,string"`
BaseVolume float64 `json:"baseVolume,string"`
QuoteVolume float64 `json:"quoteVolume,string"`
IsFrozen int
High24hr float64 `json:"high24hr,string"`
Low24hr float64 `json:"low24hr,string"`
}
答案 1 :(得分:1)
您正在尝试解码到包含加密对象的地图。这是不正确的。在结构定义中创建映射,如下所示:
type Crypto struct {
iso string `json:"BTC_BCN"` //this is the key (ex: BTC_BCN)
id int `json:"id"`
last float64 `json:"las"`
...
}
crypto := &Crypto{}
err = json.NewDecoder(reader).Decode(crypto)