在Go地图中访问嵌套值
问题描述:
我有一个随机的JSON(我不会提前知道架构),因此我编组为map[string]interface{}
。 我还有一个字符串,表示我想返回的字段值,类似于"SomeRootKey.NestValue.AnotherNestValue"
在Go地图中访问嵌套值
我希望能够返回该值。有没有一种简单的方法来访问该值,而不需要执行一些递归技巧?
答
没有递归?是的,使用循环,但没有没有不可思议的方式来做到这一点。
func getKey(m interface{}, key string) (string, bool) {
L:
for _, k := range strings.Split(key, ".") {
var v interface{}
switch m := m.(type) {
case map[string]interface{}:
v = m[k]
case []interface{}:
idx, err := strconv.Atoi(k)
if err != nil || idx > len(m) {
break L
}
v = m[idx]
default:
break L
}
switch v := v.(type) {
case map[string]interface{}:
m = v
case []interface{}:
m = v
case string:
return v, true
default:
break L
}
}
return "", false
}
使用JSON,如:
{
"SomeRootKey": {
"NestValue": {"AnotherNestValue": "object value"},
"Array": [{"AnotherNestValue": "array value"}]
}
}
您可以使用:
fmt.Println(getKey(m, "SomeRootKey.NestValue.AnotherNestValue"))
fmt.Println(getKey(m, "SomeRootKey.Array.0.AnotherNestValue"))
但将它这不会使用数组?像“a.b [0] .val” – K2xL 2014-10-09 14:01:37
@ K2xL我更新了代码。 – OneOfOne 2014-10-09 14:16:09