问题
I have a struct in Go that came from and XML resp body:
{
"pdp":{
"sellableUnits":[
{
"attributes":[
{
"id":"22555278",
"type":"size",
"value":"03.5"
}
]
}
]
}
}
type sizeJ struct {
PDP struct {
SellableUnits []struct {
Attributes []struct {
ID string `json:"id"`
Type string `json:"type"`
Val string `json:"value"`
} `json:"attributes"`
} `json:"units"`
} `json:"pdp"`
}
There are different Vals and a different ID depending on the value of Val.
回答1:
Use a for loop, with range
if you like.
func getValByID(j sizeJ, id string) string {
for _, u := range j.PDP.SellableUnits {
for _, a := range u.Attributes {
if a.ID == id {
return a.Val
}
}
}
return ""
}
func getIDByVal(j sizeJ, val string) string {
for _, u := range j.PDP.SellableUnits {
for _, a := range u.Attributes {
if a.Val == val {
return a.ID
}
}
}
return ""
}
https://play.golang.org/p/LjPrs1yGKGc
回答2:
you can use map instead of nested struct,such as
var myMap map[string]map[string]interface{}
or
var myMap map[string]interface{}
or every thing you want.
来源:https://stackoverflow.com/questions/65299372/how-to-get-json-value-based-on-other-json-values