golang无效操作:type interface {}不支持索引 [英] golang invalid operation: type interface {} does not support indexing

查看:12307
本文介绍了golang无效操作:type interface {}不支持索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是golang的新手,在阅读嵌套的JSON响应时遇到问题。

I'm new to the golang and I have problem while reading the nested JSON response.

var d interface{}
json.NewDecoder(response.Body).Decode(&d)
test :=d["data"].(map[string]interface{})["type"]

response.Body 看起来像这样

{
    "links": {
      "self": "/domains/test.one"
    },
    "data": {
        "type": "domains",
        "id": "test.one",
        "attributes": {
            "product": " Website",
            "package": "Professional",
            "created_at": "2016-08-19T11:37:01Z"
        }
    }
}

我收到的错误是这样的:

The Error I'm getting is this:

invalid operation: d["data"] (type interface {} does not support indexing)


推荐答案

d 的类型是 interface {} ,所以你不能像 d [ data] ,你需要另一个类型断言:

d is of type interface{}, so you cannot index it like d["data"], you need another type assertion:

test := d.(map[string]interface{})["data"].(map[string]interface{})["type"]
fmt.Println(test)

然后它就会工作。输出将是。请参阅 Go Playground 上的实例。

Then it will work. Output will be "domains". See a working example on the Go Playground.

还要注意,如果你声明 d 的类型为 map [string] interface {} ,那么你可以省去第一个类型断言:

Also note that if you declare d to be of type map[string]interface{}, you can spare the first type assertion:

var d map[string]interface{}
if err := json.NewDecoder(response.Body).Decode(&d); err != nil {
    panic(err)
}
test := d["data"].(map[string]interface{})["type"]
fmt.Println(test)

输出是一样的。试试去游乐场

如果您需要多次执行这些操作和类似的操作,您可能会发现我的 github.com/icza/dyno 库有用(其主要目标是帮助使用动态对象)。

If you need to do these and similar operations many times, you may find my github.com/icza/dyno library useful (whose primary goal is to aid working with dynamic objects).

这篇关于golang无效操作:type interface {}不支持索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆