doujiekeyan0622
doujiekeyan0622
2018-09-23 13:16
浏览 256

遍历JSON键和值,并同时替换golang中的指定匹配值

Is there any way to loop all over keys and values of json and thereby confirming and replacing a specific value by matched path or matched compared key or value and simultaneously creating a new interface of out of the json after being confirmed with the key new value in Golang.

This an example i saw that loops through all values https://play.golang.org/p/xtiT2iGocBg but i have no idea of replacing values by matched path or value

图片转代码服务由CSDN问答提供 功能建议

有没有办法循环遍历json的所有键和值,从而通过匹配的路径确认和替换特定值 或匹配的比较键或值,并在Golang中用键新值确认后,同时在json之外创建新接口。

我看到了一个示例,该示例遍历所有值< a href =“ https://play.golang.org/p/xtiT2iGocBg” rel =“ nofollow noreferrer”> https://play.golang.org/p/xtiT2iGocBg 但我不知道替换值 按匹配的路径或值

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dsoxcj7276
    dsoxcj7276 2018-09-26 22:18
    已采纳

    Finally! I completed the full specification of what i were looking for!!

    https://play.golang.org/p/eN4-FjaQS97

       package main
    
    import (
        "encoding/json"
        "fmt"
    )
    
    func main() {
        b := []byte(`
            {
            "iw":{"Ie":{"Itye":{"e":"eIe"}}},
    "InnerJSON2":"NoneValue",
        "outterJSON":{
            "innerJSON1":{
                "value1":10,
                "value2":22
                ,
                "InnerInnerArray": [ "test1" , "test2"],
                "InnerInnerJSONArray": [ {"fld1" : "val1"} , {"fld2" : "val2"} ]
                },
                "InnerJSON2":"NoneValue"
            }
        }
        `)
    
        f := map[string]interface{}{}
        if err := json.Unmarshal(b, &f); err != nil {
            panic(err)
        }
    
        verifyJSON(f)
        data, _ := json.MarshalIndent(f, "", "  ")
        fmt.Println(string(data))
    }
    
    func verifyJSON(bv interface{}) {
    
        var dumpJSON func(v interface{}, kn string)
    
        dumpJSON = func(v interface{}, kn string) {
            iterMap := func(x map[string]interface{}, root string) {
    
                var knf string
                if root == "root" {
                    knf = "%v/%v"
                } else {
                    knf = "%v/%v"
                }
                for k, v := range x {
    
                    switch vv := v.(type) {
    
                    case map[string]interface{}:
    
                        fmt.Printf("%s => (map[string]interface{}) ...
    ", fmt.Sprintf(knf, root, k))
    
                    case []interface{}:
                        fmt.Printf("%s => ([]interface{}) ...
    ", fmt.Sprintf(knf, root, k))
                    default:
                        fmt.Printf("%s => %v
    ", fmt.Sprintf(knf, root, k), vv)
                        x[k] = "rgk"
                    }
                    dumpJSON(v, fmt.Sprintf(knf, root, k))
                }
            }
    
            iterSlice := func(x []interface{}, root string) {
                var knf string
                if root == "root" {
                    knf = "%v/%v"
    
                } else {
                    knf = "%v/%v"
                }
                for k, v := range x {
    
                    switch vv := v.(type) {
    
                    case map[string]interface{}:
    
                        fmt.Printf("%s => (map[string]interface{}) ...
    ", fmt.Sprintf(knf, root, k))
    
                    case []interface{}:
                        fmt.Printf("%s => ([]interface{}) ...
    ", fmt.Sprintf(knf, root, k))
                    default:
    
                        fmt.Printf("%s => %v
    ", fmt.Sprintf(knf, root, k), vv)
    
                        x[k] = "rg"
                    }
    
                    dumpJSON(v, fmt.Sprintf(knf, root, k))
                }
            }
    
            switch vv := v.(type) {
            case map[string]interface{}:
                iterMap(vv, kn)
            case []interface{}:
                iterSlice(vv, kn)
            default:
    
            }
        }
        dumpJSON(bv, "root")
    }
    
    点赞 评论
  • dongying9756
    dongying9756 2018-09-23 21:07

    I finally succeeded in getting keys/values and can same time replace any values or keys now, but the last step i'm battling now is how can i get the aMap[key] and anArray[i] paths respectively of all values. E.g "test2": "TEST EACH REPLACE " has a path of outterJSON.innerJSON1.nnerInnerArray.1.test2 but can be in any format.

    https://play.golang.org/p/TNkonE8AkoJ

    package main
    
    import (
        "encoding/json"
        "fmt"   
    )
     var co=""
    func main() {
        //Creating the maps for JSON
        m := map[string]interface{}{}
    
        //Parsing/Unmarshalling JSON encoding/json
        err := json.Unmarshal([]byte(input), &m)
    
        if err != nil {
            panic(err)
        }
        parseMap(m)
    
        fmt.Println(co)
    
        data, _ := json.MarshalIndent(m,"", "  ")
        fmt.Println(string(data))
    }
    
    func parseMap(aMap map[string]interface{}) {
        for key, val := range aMap {
            switch concreteVal := val.(type) {
            case map[string]interface{}:
    
            co += key+"."
                fmt.Println(key+"NwHN")
                parseMap(val.(map[string]interface{}))
    
            case []interface{}:
            co += key+"."
                fmt.Println(key+"NHN")
                parseArray(val.([]interface{}))
    
            default:
    
            fmt.Println("OOOOO")
            aMap[key]="TEST EACH REPLACE "
                fmt.Println(key, "v:", concreteVal)
    
            }
        }
    }
    
    func parseArray(anArray []interface{}) {
        for i, val := range anArray {
            switch concreteVal := val.(type) {
            case map[string]interface{}:
    
                fmt.Println("Indexr:", i)
                parseMap(val.(map[string]interface{}))
    
            case []interface{}:
    
                fmt.Println("Indexb:", i)
                parseArray(val.([]interface{}))
    
    
            default:
            anArray[i]= "TEST EACH REPLACE ARR"
                fmt.Println("Index", i, ":", concreteVal)
    
            }
        }
    }
    
    const input = `
    {
    "ouj":"ou",
        "outterJSON":{
            "innerJSON1":{
                "value1":10,
                "value2":22
                ,
                "InnerInnerArray": [ "test1" , {"test2":"valtest2"}],
                "InnerInnerJSONArray": [ {"fld1" : "val1"} , {"fld2" : "val2"} ]
                },
                "InnerJSON2":"NoneValue"
            }
        }
        `
    
    点赞 评论

相关推荐