zoukankan      html  css  js  c++  java
  • golang depth read map

    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]
                }
            }
        }
    }
  • 相关阅读:
    81. Search in Rotated Sorted Array II (Array; Divide-and-Conquer)
    LeetCode Word Ladder
    LeetCode Word Search II
    LeetCode Invert Binary Tree
    LeetCode Implement Stack using Queues
    Bash:字符串操作
    LeetCode Basic Calculator
    LeetCode Rectangle Area
    Java 远程调试
    LeetCode Count Complete Tree Nodes
  • 原文地址:https://www.cnblogs.com/ExMan/p/11461159.html
Copyright © 2011-2022 走看看