假设JSON对象是
[map[id:id_1
fname:Form Factor
ffname:Smartphone
fuid:fid_1]
map[fname:Form Factor
ffname:Feature Phone
fuid:fid_2
id:id_1]
map[id:id_2
fname:Operating
System ffname:Android
fuid:fid_3]
map[id:id_3
ffname:Test
fuid:fid_3
fname:TestUpdated]
]
如果我需要将此地图转换为合并具有类似id值的元素。此外,fuid和ffname被组合为一个嵌套映射,其中一个新键可能已编入索引
[map[id:id_1
fname:Form Factor
newkey[1]:{fuid:fid_1 ffname:Smartphone}
newkey[2]:{fuid:fid_2 ffname:Feature Phone}]
map[id:id_2
fname:Operating System
ffname:Android fuid:fid_3]
map[id:id_3
ffname:Test
fuid:fid_3
fname:TestUpdated
}
需要进行哪些更改?
相关链接 Merge Maps in Golang
感谢
给出结果的最小代码。但肯定有一种更好的方法可以做到这一点。
func reorder() {
fdata, err := getData()
if err != nil {
fmt.Println(err)
}
var a ([]map[string]interface{})
err = json.Unmarshal(fdata, &a)
if err != nil {
fmt.Println(err)
}
fmt.Println(a)
type f1 struct {
id interface{}
fname interface{}
}
type f2 struct {
fid interface{}
ffname interface{}
}
type f3 struct {
f1 struct {
id interface{}
fname interface{}
}
f2 struct {
fid interface{}
ffname interface{}
}
}
c := make(map[int]*f3, 0)
var d *f3
for l, p := range a {
d = &f3{
f1: struct {
id interface{}
fname interface{}
}{
id: p["id"],
fname: p["fname"],
},
f2: struct {
fid interface{}
ffname interface{}
}{
fid: p["fid"],
ffname: p["ffname"],
},
}
c[l] = d
}
e := make(map[f1][]map[int]f2)
for _, h := range c {
for o, k := range c {
if h.f1.id == k.f1.id {
if h.f2.fid != k.f2.fid {
e[h.f1] = append(e[h.f1], map[int]f2{
o: k.f2,
})
fmt.Println(e)
}
} else {
if o == 0 {
var g []map[int]f2
g = append(g, map[int]f2{
o: k.f2,
})
e[h.f1] = g
}
}
}
}
fmt.Println("final transformed map..")
fmt.Println(e)
}