如何将这个嵌套的JSON解组到go对象中?
我有一个类似于此的JSON对象:如何将这个嵌套的JSON解组到go对象中?,json,go,Json,Go,我有一个类似于此的JSON对象: { "prices": { "7fb832f4-8041-4fe7-95e4-6453aeeafc93": { "diesel": 1.234, "e10": 1.234, "e5": 1.234, "status": "open" }, "92f703e8-0b3c-46da-9948-25cb1a6a1514": { "diesel": 1.234,
{
"prices": {
"7fb832f4-8041-4fe7-95e4-6453aeeafc93": {
"diesel": 1.234,
"e10": 1.234,
"e5": 1.234,
"status": "open"
},
"92f703e8-0b3c-46da-9948-25cb1a6a1514": {
"diesel": 1.234,
"e10": 1.234,
"e5": 1.234,
"status": "open"
}
}
我不知道如何在不丢失每个子项的唯一ID字段的情况下将其解组到GO对象中,这对我来说是重要的信息。您可以使用带有字符串键的
映射来保留每个子项的唯一ID:
type Object struct {
Prices map[string]*Price `json:"prices"`
}
type Price struct {
Diesel float32 `json:"diesel"`
E10 float32 `json:"e10"`
E5 float32 `json:"e5"`
Status string `json:"status"`
}
然后,例如,可以在取消编组的对象上循环:
for id, price := range o.Prices {
fmt.Printf("%s %v\n", id, price)
}
使用地图:
type Station struct {
Diesel float64
E10 float64
E15 float64
Status string
}
type Data struct {
Prices map[string]*Station
}
非常感谢您。那帮我分配了!添加json标记,因为json键和结构的字段之间不匹配。@T.Claverie字段标记不是必需的。看,我不知道,我以为它是区分大小写的。谢谢!