如何使用javascript获取嵌套的Json对象的名称

时间:2016-02-05 12:57:49

标签: javascript jquery json

有时在JSON中有一些值不作为名称值对存在,而是作为名称然后它们的属性存在,下面例如在objectOne,ObjectTwo和objectThree下面的JSON中。问题是,如果我事先不知道这些名称将会是什么,那么名称会不断改变我如何提取它们?但数据结构将是相同的

 {
        "Number of objects": 3,
        "Devices": {
            "objectOne": {
                "name": "10",
                "name1": "50"
            },
            "objectTwo": {
                "name": "20",
                "name1": "30"
            },
            "objectThree": {
                "name": "40",
                "name1": "80"
            }
        }
    }

1 个答案:

答案 0 :(得分:3)

您可以尝试使用Object.keys方法。

示例:

var yourJson = {
    "Number of objects": 3,
    "Devices": {
        "objectOne": {
            "name": "10",
            "name1": "50"
        },
        "objectTwo": {
            "name": "20",
            "name1": "30"
        },
        "objectThree": {
            "name": "40",
            "name1": "80"
        }
    }
}
var keys = Object.keys(yourJson.Devices); // Array with "objectOne", "objectTwo" and "objectThree"

更新: 然后你可以这样访问objectTwo:

var objectTwo = yourJson.Devices[keys[1]];

如果你需要遍历所有,那就更好了:

for (var key in keys) {
    // key = "objectOne", then "objectTwo", then "objectThree"
    var objectN = yourJson.Devices[key]; // the device object
}