如何基于其他JSON值获取JSON值

如何基于其他JSON值获取JSON值,json,xml,go,Json,Xml,Go,我在Go中有一个结构,它来自和XML resp body: { "pdp":{ "sellableUnits":[ { "attributes":[ { "id":"22555278",

我在Go中有一个结构,它来自和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和不同的ID,具体取决于Val的值。

您可以使用map而不是嵌套结构,例如

var myMap map[string]map[string]interface{}

或者你想要的任何东西。

使用循环,如果你愿意,使用
范围

func getValByID(j sizeJ,id字符串)字符串{
对于u,u:=范围j.PDP.SellableUnits{
对于u,a:=范围u.属性{
如果a.ID==ID{
返回a.Val
}
}
}
返回“”
}
func getIDByVal(j sizeJ,val string)字符串{
对于u,u:=范围j.PDP.SellableUnits{
对于u,a:=范围u.属性{
如果a.Val==Val{
返回a.ID
}
}
}
返回“”
}

好的,但当我在resp主体上使用此结构时,如何根据Val记录ID?为什么运行此结构时会得到空白输出?@Salvatoretinpani,因为您提供的输入为空或不正确。你可以在链接中看到这种方法是有效的。没有错,我的输入与tags@SalvatoreTimpani看,没有人能调试他们看不到的东西。问题中没有
标记。链接中的解决方案使用伪json,因为您没有提供伪json。如果您的数据不同,为什么不将其包括在问题中?刚才添加的
var myMap map[string]interface{}