遍历JSON键和值,并同时替换golang中的指定匹配值 [英] Loop through JSON keys and values and same time replacing specify matched value in golang
问题描述
是否有任何方法可以循环遍历json的所有键和值,从而通过匹配的路径或匹配的比较键或值确认和替换特定值,并在用键确认后同时在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.
我看到的这个示例遍历所有值 https://play.golang.org/p /xtiT2iGocBg ,但我不知道用匹配的路径或值替换值
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
推荐答案
最后!我完成了我所寻找的全部规格!
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{}) ...\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")
}
这篇关于遍历JSON键和值,并同时替换golang中的指定匹配值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!