[英]How to unmarshal this nested JSON into go objects?
I have a JSON object similar to this one: 我有一个与此对象相似的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,
"e10": 1.234,
"e5": 1.234,
"status": "open"
}
}
I am not sure how to unmarshal this into an GO object without losing the unique ID field of each sub-item which is important information for me. 我不确定如何在不丢失每个子项目的唯一ID字段的情况下将其解组到GO对象,这对我来说是重要的信息。
You can use a map
with string keys to preserve the unique IDs of each sub-price: 您可以使用带有字符串键的map
来保留每个子价格的唯一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"`
}
Then, for example, you could loop over the unmarshaled object: 然后,例如,您可以遍历未编组的对象:
for id, price := range o.Prices {
fmt.Printf("%s %v\n", id, price)
}
https://play.golang.org/p/aPhvGdtFC_ https://play.golang.org/p/aPhvGdtFC_
Use a map: 使用地图:
type Station struct {
Diesel float64
E10 float64
E15 float64
Status string
}
type Data struct {
Prices map[string]*Station
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.