我正在嘗試將這個簡單的 python 函式轉換為 golang,但面臨此錯誤的問題
panic: interface conversion: interface {} is string, not float64
python
def binance(crypto: str, currency: str):
import requests
base_url = "https://www.binance.com/api/v3/avgPrice?symbol={}{}"
base_url = base_url.format(crypto, currency)
try:
result = requests.get(base_url).json()
print(result)
result = result.get("price")
except Exception as e:
return False
return result
這是 golang 版本(更長的代碼和比應該更復雜的代碼)
func Binance(crypto string, currency string) (float64, error) {
req, err := http.NewRequest("GET", fmt.Sprintf("https://www.binance.com/api/v3/avgPrice?symbol=%s%s", crypto, currency), nil)
if err != nil {
fmt.Println("Error is req: ", err)
}
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("error in send req: ", err)
}
respBody, _ := ioutil.ReadAll(resp.Body)
var respMap map[string]interface{}
log.Printf("body=%v",respBody)
json.Unmarshal(respBody,&respMap)
log.Printf("response=%v",respMap)
price := respMap["price"]
log.Printf("price=%v",price)
pricer := price.(float64)
return pricer, err
}
那么我在這里做錯了什么?以前我有錯誤cannot use price (type interface {}) as type float64 in return argument: need type assertion,現在我嘗試了型別斷言,pricer := price.(float64)現在這個錯誤
panic: interface conversion: interface {} is string, not float64
uj5u.com熱心網友回復:
它在錯誤中告訴你,price是一個字串,而不是一個 float64,所以你需要做(大概):
pricer := price.(string)
return strconv.ParseFloat(pricer, 64)
更好的方法可能是改為
type response struct {
Price float64 `json:",string"`
}
r := &response{}
respBody, _ := ioutil.ReadAll(resp.Body)
err := json.Unmarshal(respBody, r)
return r.Price, err
“字串”選項表示欄位以 JSON 形式存盤在 JSON 編碼的字串中。它僅適用于字串、浮點、整數或布爾型別的欄位。
https://pkg.go.dev/encoding/json#Marshal
uj5u.com熱心網友回復:
錯誤已經告訴你:價格是一個字串。所以它可能來自一個看起來像這樣的 JSON:
{
"price": "123"
}
但不是
{
"price": 123
}
第一個解組為字串。第二個解組為 float64。
在您的情況下,您必須決議它:
pricer,err := strconv.ParseFloat(price.(string),64)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/404464.html
標籤:
