获取json的键和参数值

时间:2017-04-01 11:29:15

标签: json

我希望借助迭代获得JSON Object键及其元素的各个值

我的json会是这样的: -

var a=
{
    "HYDROGEN": {
        "atomic_number": 1,
        "abbreviation": "H",
        "atomic_weight": 1.008
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    }}

2 个答案:

答案 0 :(得分:1)

var a=
{
    "HYDROGEN": {
        "atomic_number": 1,
        "abbreviation": "H",
        "atomic_weight": 1.008
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    },
    "HELIUM": {
        "atomic_number": 2,
        "abbreviation": "He",
        "atomic_weight": 4.003
    }}

  for (i=0;i<1;i++)
  {
  console.log(Object.keys(a)[i])
  console.log(a[Object.keys(a)[i]].atomic_number)
  console.log(a[Object.keys(a)[i]].atomic_weight)
  console.log(a[Object.keys(a)[i]].abbreviation)
}

答案 1 :(得分:0)

您可以动态检索{a}对象的[keys]和[values]:

for (var sIndexKey in a) {
    if (a.hasOwnProperty(sIndexKey) === true) {
        var oJsonData = a[sIndexKey]; // in this case the 2 objects inside your {a} object
        var sObjectKeys = Object.keys(oJsonData); //e.g atomic_number / abbreviation / atomic_weight
        for (var iIndex = 0; iIndex < sObjectKeys.length; iIndex++) {
            var sJsonKeys = sObjectKeys[iIndex];
            var sJsonValues = oJsonData[sJsonKeys];
            console.log(sJsonKeys);
            console.log(sJsonValues);
        }
    }
}

以下是jsfiddle以供进一步参考:http://jsfiddle.net/q37ehka9/

希望这有助于您的案例