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

时间:2014-10-23 21:48:28

标签: json go

在GO中,我怎样才能从下面的json数据中获得一个年龄数组

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

}

最终结果应该是年龄的集合,例如。 [31,32,33,34]

1 个答案:

答案 0 :(得分:2)

创建一个与布局匹配的结构,并从中创建年龄切片:

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)

}