码迷,mamicode.com
首页 > 其他好文 > 详细

golang depth read map

时间:2019-09-04 21:30:49      阅读:160      评论:0      收藏:0      [点我收藏+]

标签:output   play   release   hal   ring   one   span   sed   second   

Foreword: I optimized and improved the below solution, and released it as a library here: github.com/icza/dyno.


The cleanest way would be to create predefined types (structures struct) that model your JSON, and unmarshal to a value of that type, and you can simply refer to elements using Selectors (for struct types) and Index expressions (for maps and slices).

However if your input is not of a predefined structure, I suggest you the following 2 helper functions: get() and set(). The first one accesses (returns) an arbitrary element specified by an arbitrary path (list of string map keys and/or int slice indices), the second changes (sets) the value specified by an arbitrary path (implementations of these helper functions are at the end of the answer).

You only have to include these 2 functions once in your project/app.

And now using these helpers, the tasks you want to do becomes this simple (just like the python solution):

fmt.Println(get(d, "key3", 0, "c2key1", "c3key1"))
set("NEWVALUE", d, "key3", 0, "c2key1", "c3key1")
fmt.Println(get(d, "key3", 0, "c2key1", "c3key1"))

Output:

change1
NEWVALUE

Try your modified app on the Go Playground.

Note - Further Simplification:

You can even save the path in a variable and reuse it to simplify the above code further:

path := []interface{}{"key3", 0, "c2key1", "c3key1"}

fmt.Println(get(d, path...))
set("NEWVALUE", d, path...)
fmt.Println(get(d, path...))

And the implementations of get() and set() are below. Note: checks whether the path is valid is omitted. This implementation uses Type switches:

func get(m interface{}, path ...interface{}) interface{} {
    for _, p := range path {
        switch idx := p.(type) {
        case string:
            m = m.(map[string]interface{})[idx]
        case int:
            m = m.([]interface{})[idx]
        }
    }
    return m
}

func set(v interface{}, m interface{}, path ...interface{}) {
    for i, p := range path {
        last := i == len(path)-1
        switch idx := p.(type) {
        case string:
            if last {
                m.(map[string]interface{})[idx] = v
            } else {
                m = m.(map[string]interface{})[idx]
            }
        case int:
            if last {
                m.([]interface{})[idx] = v
            } else {
                m = m.([]interface{})[idx]
            }
        }
    }
}

golang depth read map

标签:output   play   release   hal   ring   one   span   sed   second   

原文地址:https://www.cnblogs.com/ExMan/p/11461159.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!