drxdn40242 2018-02-23 16:18
浏览 63
已采纳

通过接口获取结构的值

I'm trying to parse this petition (https://www.binance.com/api/v1/depth?symbol=MDABTC&limit=500)

I was having tons of problems to create an struct for it, so I used an automated tool, this is what my struct looks like:

type orderBook struct {
    Bids         [][]interface{} `json:"Bids"`
    Asks         [][]interface{} `json:"Asks"`
}

I recover and parse the petition by doing:

url := "https://www.binance.com/api/v1/depth?symbol=MDABTC&limit=500"
resp, err := http.Get(url)
if err != nil {
    panic(err)
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
    panic(err)
}else{
    book := orderBook{}
if err := json.Unmarshal(body, &book); err != nil {
    panic(err)
}

But whenever I try to make an operation with the struct, like:

 v := book.Asks[i][0] * book.Asks[i][1]

I get an error:

invalid operation: book.Asks[i][0] * book.Asks[i][1] (operator * not defined on interface)

How do I define it? Do I need to create an struct for bids/asks, if so, how would that look like?

Sorry if this seems basic, I just started learning go.

  • 写回答

2条回答 默认 最新

  • duangan6731 2018-02-23 16:37
    关注

    In Golang Spec

    For an expression x of interface type and a type T, the primary expression

    x.(T)
    

    asserts that x is not nil and that the value stored in x is of type T. The notation x.(T) is called a type assertion.

    Fetching an underlying value of string type you need to type assert to string from interface.

    books.Asks[0][0].(string)
    

    For performing an arithmetic operation on same you needs to convert string into float64 to take into account decimal values

    v := strconv.ParseFloat(books.Asks[0][0].(string), 64) * strconv.ParseFloat(books.Asks[0][1].(string), 64)
    

    Checkout code on Go playground

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 统计大规模图中的完全子图问题
  • ¥15 使用LM2596制作降压电路,一个能运行,一个不能
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路
  • ¥15 经gamit解算的cors站数据再经globk网平差得到的坐标做形变分析
  • ¥15 phython读取excel表格报错 ^7个 SyntaxError: invalid syntax 语句报错
  • ¥20 @microsoft/fetch-event-source 流式响应问题
  • ¥15 ogg dd trandata 报错
  • ¥15 高缺失率数据如何选择填充方式