小编典典

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

go

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

我看到的这个示例遍历所有值https://play.golang.org/p/xtiT2iGocBg,但是我不知道用匹配的路径或值替换值


阅读 477

收藏
2020-07-02

共1个答案

小编典典

最后!我完成了我所寻找的全部规格!!

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{}) ...\n", fmt.Sprintf(knf, root, k))

                case []interface{}:
                    fmt.Printf("%s => ([]interface{}) ...\n", fmt.Sprintf(knf, root, k))
                default:
                    fmt.Printf("%s => %v\n", 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{}) ...\n", fmt.Sprintf(knf, root, k))

                case []interface{}:
                    fmt.Printf("%s => ([]interface{}) ...\n", fmt.Sprintf(knf, root, k))
                default:

                    fmt.Printf("%s => %v\n", 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")
}
2020-07-02