我有一个泛型类型的数组interface{},我想检查该数组是否在其 JSON 对象之一中包含某个值。
history := reflect.ValueOf(historyInterface)
for i := 0; i < history.Len(); i++ {
// here I can get a map object
test := history.Index(i)
// then I tried to access the id property of the object
// but here it fails
fmt.Println("test", test["id"].(string))
}
Run Code Online (Sandbox Code Playgroud)
以下是每次迭代的测试:
first iteration
map[id:5afbff19bf07c79c19ed9af9 date:Saturday, January 21, 2017 9:21 PM certitude:33]
second iteration
map[id:afbff198658487a3e3e376b date:Thursday, March 3, 2016 2:24 PM certitude:30]
Run Code Online (Sandbox Code Playgroud)
无效操作:test["id"](类型reflect.Value不支持索引)
如果historyInterface是通过将 JSON 解组为 来创建的interface{},则映射的类型为map[string]interface{}。使用类型断言来获取该类型的映射:
history := reflect.ValueOf(historyInterface)
for i := 0; i < history.Len(); i++ {
test := history.Index(i).Interface().(map[string]interface{})
fmt.Println("test", test["id"].(string))
}
Run Code Online (Sandbox Code Playgroud)
同样基于对数据源的假设,应用程序可以使用类型断言而不是反射。
history := historyInterface.([]interface{})
for _, m := range history {
test := m.(map[string]interface{})
fmt.Println("test", test["id"].(string))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1364 次 |
| 最近记录: |