【发布时间】:2022-08-13 23:04:22
【问题描述】:
我想写一个通用函数func GetVal(map[interface{}]interface{}, key interface{}) interface{}。这将需要一个映射和一个键来搜索并返回值或 nil。
地图可以有任何数据类型,并且可以进入任何级别的嵌套。例如,
var s1 = \"S1\"
var s2 = \"S2\"
var s3 = s1 + \"==\" + s2 + \"==S3\"
var s4 = s3 + \"==S4\"
var nestedMap = map[interface{}]interface{}{
\"data\": map[interface{}]interface{}{
\"TEST_KEY\": \"1234353453\",
\"metadata\": map[interface{}]interface{}{
\"created_time\": \"2022-08-06\",
},
\"custom_metadata\": map[interface{}][]interface{}{
\"destroyed\": []interface{}{
&s1,
map[string]interface{}{
\"auth\": []interface{}{
\"val3\", \"val4\", \"val45\",
},
},
},
},
&s2: &[]*string{
&s1, &s2,
},
&s1: &[]int{
10, 20, 233,
},
123: &s3,
},
s3: []interface{}{
[]interface{}{
map[string]*string{
s4: &s4,
},
},
},
}
预期返回值
GetVal(nestedMap, \"metadata\") 应该返回 {\"created_time\": \"2022-08-06\"}
GetVal(nestedMap, \"destroyed\") 应该返回
{ &s1,
map[string]interface{}{
\"auth\": []interface{}{
\"val3\", \"val4\", \"val45\",
},
},
}
有没有办法在没有外部库的情况下做到这一点?
这个问题看起来类似于 Accessing Nested Map of Type map[string]interface{} in Golang 但在我的情况下,字段不受限制或始终相同
-
这是一个可能的重复:
get()和set()执行该操作(旨在编辑任意 JSON):Taking a JSON string, unmarshaling it into a map, editing, and marshaling it into a byte slice seems more complicated then it should be -
@icza 这使用完整路径来存储和检索在我的情况下不存在的值。我只有一把钥匙
-
递归地遍历地图。如果键匹配,则返回值。否则使用类型开关检查值是映射还是切片,如果是,则进行递归调用。
-
这看起来像 XPath 一样的遍历是想要的。如果将
nestedmap转换为json 文档,则antchfx/xpath 的jsonquery 实现可以处理这种情况。不确定json.Marshal是否支持将此类映射转换为 json。如果它比jsonquery.Find(doc, \"//metadata\")可以在这里工作。
标签: go