douxie2007 2014-10-23 21:48
浏览 403
已采纳

GO-从嵌套的JSON对象获取属性值的数组

In GO, how can I get an array of the ages from the json Data below

{
"people": {
    "female": [
        {
            "age": 31,
            "id": 1
        },
        {
            "age": 32,
            "id": 2
        }
    ],
    "male": [
        {
            "age": 33,
            "id": 3
        },
        {
            "age": 34,
            "id": 5
        }
    ]
}

}

End result should be a collection of ages eg. [31,32,33,34]

  • 写回答

1条回答 默认 最新

  • douxie2029 2014-10-23 22:02
    关注

    Create a struct that matches the layout and create the ages slice from it:

    func main() {
        var s struct {
            People struct {
                Female []struct {
                    Age int
                }
                Male []struct {
                    Age int
                }
            }
        }
        err := json.Unmarshal([]byte(j), &s)
        var ages []int
        for _, p := range s.People.Female {
            ages = append(ages, p.Age)
        }
        for _, p := range s.People.Male {
            ages = append(ages, p.Age)
        }
        fmt.Println(err, ages)
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?