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]
                }
            }
        }
    }
  • 相关阅读:
    vue点击实现箭头的向上与向下
    ES6中箭头函数加不加大括号的区别
    angular图片的两种表达方式
    通过添加类名实现样式的变化
    angular中路由跳转并传值四种方式
    Sublime Text 3 设置文件详解(settings文件)
    Second:eclipse配置Tomcat
    First:安装配置JDK and 部署Tomcat
    本地环境代码一码云一服务器代码部署
    2.sublime设置本地远程代码同步
  • 原文地址:https://www.cnblogs.com/ExMan/p/11461159.html
Copyright © 2011-2022 走看看