How to get JSON value based on other JSON values

旧街凉风 提交于 2020-12-27 05:32:29

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!