【问题标题】:type interface {} does not support indexingtype interface {} 不支持索引
【发布时间】:2019-08-18 07:31:51
【问题描述】:

我想从bid 获取值。 我已经尝试过data.(map[string]interface{}),但没有成功。

当我尝试时,它说:

"接口转换:interface {}是[]interface {},而不是map[string]interface {}"

请帮帮我...

这是我的代码。

    url := "https://api.binance.com/api/v1/depth?symbol=RENBTC"
    a, _ := http.Get(url)
    e, _ := ioutil.ReadAll(a.Body)

    var data map[string]interface{}

    _ = json.Unmarshal([]byte(e), &data)
    bid := data["bids"]
    fmt.Println(bid[0])

【问题讨论】:

  • 如果错误提示 "interface {} is []interface {}, not map[string]interface {}" 那么可以尝试输入[]interface {}值而不是地图,例如bid.([]interface{})[0].
  • 查看相关问题123
  • 还有十几个其他问题包含这个确切的错误:stackoverflow.com/…(以及更多相关答案)

标签: go


【解决方案1】:

你需要类型断言 bid, ok := data["bids"].([]interface{})
见:Explain Type Assertions in Go

试试这个:

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"
)

func main() {
    url := "https://api.binance.com/api/v1/depth?symbol=RENBTC"
    a, err := http.Get(url)
    if err != nil {
        log.Fatal(err)
    }

    buf, err := ioutil.ReadAll(a.Body)
    if err != nil {
        log.Fatal(err)
    }

    var data map[string]interface{}
    err = json.Unmarshal([]byte(buf), &data)
    if err != nil {
        log.Fatal(err)
    }

    bid, ok := data["bids"].([]interface{})
    if !ok {
        log.Fatal("not ok")
    }

    s, ok := bid[0].([]interface{})
    if !ok {
        log.Fatal("not ok")
    }
    fmt.Println(s)
}

输出:

[0.00000603 5122.00000000]

【讨论】:

    猜你喜欢
    • 2018-05-09
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2022-11-27
    • 2014-04-23
    • 2019-11-12
    • 2018-10-29
    • 2011-10-26
    相关资源
    最近更新 更多