如何基于其他JSON值获取JSON值 [英] How to get JSON value based on other JSON values
本文介绍了如何基于其他JSON值获取JSON值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在Go中有一个结构,它来自XML主体:
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"`
}
根据Val的值,存在不同的Val和不同的ID.
There are different Vals and a different ID depending on the value of Val.
推荐答案
使用 for
循环,如果愿意,可以使用range
.
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
这篇关于如何基于其他JSON值获取JSON值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文