package main
import (
"encoding/json"
"fmt"
)
func main() {
// 生成map格式字符串
ma1 := make(map[string]interface{})
ma2 := make(map[string]interface{})
ma3 := make(map[string]interface{})
ma4 := make(map[string]interface{})
ma1["a1"] = ma2
ma1["a2"] = 3
ma1["a3"] = 4
ma2["b1"] = 22
ma2["b2"] = 33
ma2["b3"] = []int{1,2,3}
ma2["b4"] = ma3
ma3["c1"] = 55
ma3["c3"] = 88
ma4["d1"] = 66
ma4["d2"] = 77
ma3["c2"] = ma4
// 将map格式字符串转化为json
mjson,_ :=json.Marshal(ma1)
fmt.Println(string(mjson))
fmt.Println("-----------------------------------")
var k string
var s string
map3:= make(map[string]interface{})
err := json.Unmarshal(mjson, &map3)
if err != nil {
fmt.Println(err)
}
s = jsonToKV(k,s,map3)
fmt.Println(s)
}
func jsonToKV(key string,str string ,data interface{}) string {
_,ok := data.(map[string]interface{})
if ok {
for k,v := range data.(map[string]interface{}) {
if len(key) > 0 {
k = key + "." + k
}
_,ok = v.(map[string]interface{})
if ok {
str = jsonToKV(k,str,v)
} else {
if len(str) == 0 {
str = str + k + "=" + fmt.Sprintf("%v",v)
} else {
str = str + " "+ k + "=" + fmt.Sprintf("%v",v)
}
}
}
}
return str
}
|