我正在努力获取以下接口(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/