package main
import (
"fmt"
)
func main() {
m1 := map[string]interface{}{
"a": 1,
"b": 2,
"c": map[string]interface{}{
"d": 3,
"e": 4,
},
"f": 5,
}
m2 := make(map[string]interface{})
for k, v := range m1 {
if mm, ok := v.(map[string]interface{}); ok {
for kx, vx := range mm {
m2[k+"."+kx] = vx
}
} else {
m2[k] = v
}
}
for k, v := range m2 {
fmt.Println(k, v)
}
fmt.Println("Hello, playground")
}
golang golang flatten嵌套地图
type Data map[string]interface{}
func main() {
var data Data
data = Data{
"A": 1,
"B": 2,
"C": Data{
"D": 3,
"E": 4,
"G": Data{
"H": 123,
"Q": 456,
},
},
"F": 5,
"DATE": time.Now(),
}
newMap1 := flattenMap(data)
log.Printf("%v\n", newMap1)
}
func flattenMap(m Data) Data {
d := make(Data)
for k, v := range m {
v1, ok := v.(Data)
if ok {
flatMap(d, v1, k)
} else {
d[k] = v
}
}
return d
}
func flatMap(d, m Data, oldKey string) {
for k, v := range m {
v1, ok := v.(Data)
if ok {
flatMap(d, v1, oldKey+"."+k)
} else {
d[oldKey+"."+k] = v
}
}
}