3 回答
TA贡献1802条经验 获得超5个赞
TA贡献1890条经验 获得超9个赞
这是另一种选择。
package main
import (
"encoding/json"
"fmt"
)
var raw = `
{
"details": [
{
"attdetails": [
{
"id": "a48c8539-caaf-49a5-9346-8e88e60e7af4",
"name": "compute01"
},
{
"id": "a48c8539-caaf-49a5-9346-8e88e60e7af4",
"name": "compute02"
}
],
"name": "item1"
},
{
"attdetails": [
{
"id": "85bdafa7-274e-4180-b76f-12f390a274fc",
"name": "compute03"
},
{
"id": "85bdafa7-274e-4180-b76f-12f390a274fc",
"name": "compute04"
}
],
"name": "item1"
}
]
}
`
type Data struct {
Details []struct {
AttDetails []struct {
Id string `json:"id"`
Name string `json:"name"`
} `json:"attdetails"`
Name string `json:"name"`
} `json:"details"`
}
func main() {
var data Data
err := json.Unmarshal([]byte(raw), &data)
if err != nil {
fmt.Println(err)
}
output := map[string][]map[string]string{}
for _, detail := range data.Details {
for _, attdetail := range detail.AttDetails {
output[detail.Name] = append(output[detail.Name], map[string]string{
attdetail.Name: attdetail.Id,
})
}
}
// b, _ := json.Marshal(output) // non-pretty version
b, _ := json.MarshalIndent(output, "", "\t")
fmt.Println(string(b))
}
TA贡献1804条经验 获得超8个赞
func jsonToMap(jsonStr string) map[string]interface{} {
result := make(map[string]interface{})
json.Unmarshal([]byte(jsonStr), &result)
return result
}
示例 - https://goplay.space/#ra7Gv8A5Heh
TA贡献2080条经验 获得超4个赞
我能够使用以下代码获得所需的结构:
var cs = make(map[string][]map[string]string)
for _, a := range atts{
_, ok := childrens[a.Name]
if !ok {
cs[a.Name] = make([]map[string]string, 0)
}
var c = make(map[string]string)
for _, each := range a.Details {
c[each.Name] = each.Value
}
cs[a.Name] = append(cs[a.ClassName], c)
}
- 3 回答
- 0 关注
- 148 浏览
添加回答
举报