3 回答

TA貢獻(xiàn)1802條經(jīng)驗(yàn) 獲得超5個(gè)贊
我認(rèn)為像下面這樣的東西應(yīng)該可以解決問(wèn)題,
https://play.golang.org/p/YbZ1niXyFBR
它并不完全是您想要的結(jié)構(gòu),但應(yīng)該為您提供調(diào)整方向的要點(diǎn)。

TA貢獻(xiàn)1890條經(jīng)驗(yàn) 獲得超9個(gè)贊
這是另一種選擇。
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貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊
func jsonToMap(jsonStr string) map[string]interface{} {
result := make(map[string]interface{})
json.Unmarshal([]byte(jsonStr), &result)
return result
}
示例 - https://goplay.space/#ra7Gv8A5Heh

TA貢獻(xiàn)2080條經(jīng)驗(yàn) 獲得超4個(gè)贊
我能夠使用以下代碼獲得所需的結(jié)構(gòu):
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 關(guān)注
- 228 瀏覽
添加回答
舉報(bào)