如何在解析JSON时获取对象名称

时间:2014-11-22 16:12:16

标签: jquery json object each

说我的json看起来像这样:

{
    "Heading1":{"internal 1":[0,0,0,1],"internal 2":[0,0,0,0]},
    "Heading2":{"internal 1":[0,0,0,0],"internal 2":[0,0,0,0]}
}

我编写了以下jquery函数

$.each(jsonData, function(index, data){
        console.log(data);
    });

但这只会给我单独的对象:

{"internal 1":[0,0,0,1],"internal 2":[0,0,0,0]}

{"internal 1":[0,0,0,0],"internal 2":[0,0,0,0]}

但我如何获取" Heading" (每个对象名称)?是否有inbulit属性?比如说data.name或data.id还是什么?

1 个答案:

答案 0 :(得分:2)

使用$.each,您定义的index属性实际上是关键:

$.each(jsonData, function(key, value){
    console.log(key) //Heading1
})

或者,for in

for (var key in jsonData) {
    console.log(key) //Heading1
    console.log(jsonData[key]) //{"internal 1":[0,0,0,1],"internal 2":[0,0,0,0]}
}