go - 如何在 Go 中迭代 []interface{}

标签 go interface type-assertion

我正在努力获取以下接口(interface)的键和值,这是对Execute 返回的结果进行JSON 编码的结果。如 this example 所示:

[
    [
        {
            "id": 36,
            "label": "TestThing",
            "properties": {
                "schema__testBoolean": [
                    {
                        "id": 40,
                        "value": true
                    }
                ],
                "schema__testInt": [
                    {
                        "id": 39,
                        "value": 1
                    }
                ],
                "schema__testNumber": [
                    {
                        "id": 38,
                        "value": 1.0879834
                    }
                ],
                "schema__testString": [
                    {
                        "id": 37,
                        "value": "foobar"
                    }
                ],
                "uuid": [
                    {
                        "id": 41,
                        "value": "7f14bf92-341f-408b-be00-5a0a430852ee"
                    }
                ]
            },
            "type": "vertex"
        }
    ]
]

reflect.TypeOf(result) 结果:[]interface{}

我用它来遍历数组:

s := reflect.ValueOf(result)
for i := 0; i < s.Len(); i++ {
  singleVertex := s.Index(i).Elem() // What to do here?
}

但我遇到了以下错误:

reflect.Value.Interface: cannot return value obtained from unexported field or method

最佳答案

如果您知道那是您的数据结构,则根本没有理由使用反射。只需使用类型断言:

for key, value := range result.([]interface{})[0].([]interface{})[0].(map[string]interface{}) {
    // key == id, label, properties, etc
}

关于go - 如何在 Go 中迭代 []interface{},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51172562/

相关文章:

json - 在 golang 中检查 JSON 字符串是否有效

typescript - 我可以在不通过断言强制类型的情况下修复此 typescript 编译器错误吗?

参数中的 typescript 类型断言

interface - 接口(interface)的方法

java - 为实现接口(interface)的类实现可序列化

typescript - "as const"在 TypeScript 中是什么意思,它的用例是什么?

go - 选择 block 如何等待 ctx.Done() 操作?

go - 如何在 Go 中解析包含各种元素的巨大 XML 文件?

golang 数据库/sql 使用 pq

c# - 如何避免在更新接口(interface)后必须更新所有实现类?