小编Pet*_*ton的帖子

如何高效地扁平化地图?

我的应用程序需要获取大量嵌套实例map[string]interface{}并将它们转换为扁平化地图。

例如:

{
                "foo": {
                    "jim":"bean"
                },
                "fee": "bar",
                "n1": {
                    "alist": [
                        "a",
                        "b",
                        "c",
                        {
                            "d": "other",
                            "e": "another"
                        }
                    ]
                },
                "number": 1.4567,
                "bool":   true
}
Run Code Online (Sandbox Code Playgroud)

后:

json.Unmarshal([]byte(input), &out)
result = Flatten(m.(map[string]interface{}))
Run Code Online (Sandbox Code Playgroud)

变成:

{
                "foo.jim":      "bean",
                "fee":          "bar",
                "n1.alist.0":   "a",
                "n1.alist.1":   "b",
                "n1.alist.2":   "c",
                "n1.alist.3.d": "other",
                "n1.alist.3.e": "another",
                "number":       1.4567,
                "bool":         true,
}
Run Code Online (Sandbox Code Playgroud)

目前我正在使用以下代码:

func Flatten(m map[string]interface{}) map[string]interface{} {
    o := map[string]interface{}{}
    for k, v := range m {
        switch child := v.(type) {
        case …
Run Code Online (Sandbox Code Playgroud)

garbage-collection memory-leaks pass-by-reference go flatten

4
推荐指数
1
解决办法
7159
查看次数