我有一個看起來像這樣JSON數據:如何在Golang中正確解組無關鍵JSON數組?
[
{
"globalTradeID": 64201000,
"tradeID": 549285,
"date": "2016-11-11 23:51:58",
"type": "buy",
"rate": "10.33999779",
"amount": "0.02176472",
"total": "0.22504715"
},
{
"globalTradeID": 64200631,
"tradeID": 549284,
"date": "2016-11-11 23:48:39",
"type": "buy",
"rate": "10.33999822",
"amount": "0.18211700",
"total": "1.88308945"
}...
]
我試圖通過定義一個類型來解讀這個JSON:
type TradeHistoryResponse []TradeHistoryInfo
type TradeHistoryInfo struct {
GlobalTradeID int64 `json:"globalTradeID"`
TradeID int64 `json:"tradeID"`
Date string `json:"date"`
Type string `json:"type"`
Rate float64 `json:"rate,string"`
Amount float64 `json:"amount,string"`
Total float64 `json:"total,string"`
}
再拉拉JSON數據像這樣:
//Read response
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("[Poloniex] (doRequest) Failed to parse response for query to %s! (%s)", reqURL, err.Error())
}
//Convert JSON to struct
var THR TradeHistoryResponse
err = json.Unmarshal(body, &THR)
if err != nil {
return nil, fmt.Errorf("[Poloniex] (doRequest) Failed to convert response into JSON for query to %s! (%s)", reqURL, err.Error())
}
我收到以下錯誤:
(json: cannot unmarshal object into Go value of type poloniex.TradeHistoryResponse)
我最好的猜測爲什麼Unmarshall不起作用是因爲數組無關鍵?
希望對此事做一些澄清,說明如何最好地實現這一目標。
我不確定你的意思是「數組無關鍵」,或者是什麼問題。您的示例代碼有效:https://play.golang.org/p/zbybX0tnRB – JimB
@ nik-kunkel您的示例代碼正常工作,請看一下https://play.golang.org/p/743MBHL3Y4。我最好的主意是你的身體不正確。大概你從身體讀到的不是那個數據。 – sadlil
@JimB和Nik是正確的,也許你應該嘗試寫入標準輸出/文件你正在檢索的身體,並檢查數組中的所有元素是否與你試圖解碼到的類型一致。 –