【问题标题】:How to return value of a key in nested map如何在嵌套映射中返回键的值
【发布时间】: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 但在我的情况下,字段不受限制或始终相同

标签: go


【解决方案1】:

这个问题有点神秘,因为这个例子过于复杂。如果您想了解有关循环函数的知识,您应该从更简单的内容开始,例如:

var nestedMap = map[string]any{
"k1": "v1",
"k2": map[string]any{
    "nestedK1": "nestedV1",
    "nestedK2": "nestedV2",
    "nestedK3": map[string]any{
        "superNestedK1" : "FOUND!!!",
    },
},}

否则,解释将是困难的。

然后您可以处理以下功能:

func GetVal(data map[string]any, key string) (result any, found bool) {
for k, v := range data {
    if k == key {
        return v, true
    } else {
        switch v.(type) {
        case map[string]any:
            if result, found = GetVal(v.(map[string]any), key); found {
                return
            }
        }
    }
}
return nil, false}

稍后你可以考虑添加对花哨的东西的支持,比如map[interface{}][]interface{}

但是,如果你真的需要这么复杂的结构,我不确定整个应用程序的设计是否可以。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-06
    • 2021-01-11
    • 1970-01-01
    • 1970-01-01
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多