无效的操作:类型接口{}不支持索引 [英] invalid operation: type interface {} does not support indexing

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

问题描述

我是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"
        }
    }
}

我得到的错误是:

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)

然后它将起作用.输出将为"domains".请参见游乐场.

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)

输出是相同的.在游乐场上尝试一下.

Output is the same. Try this one on the Go Playground.

如果您需要多次执行这些操作和类似操作,则可能会发现我的 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).

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

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