嵌套的JSON无法读取属性

时间:2017-01-16 15:39:30

标签: javascript json

我重新启动了主题:

我有点傻了。问题是我向JSON展示了一点,因为它是一个机密文件。 JSON的嵌套方式如下:

"01": {
    "titel": "json",
    "a1": 001,
    "a2": {
        "b1": 002,
        "b2": 003,
        "b3": "b3"
    },
    "a3": {
        "c1": "c1",
        "c2": "c2",
        "c3": 003,
        "c4": 004,
        "c5": 005,
        "c6": {
            "d1": 001,
            "d2": 002,
            "d3": 003
        }
    },
    "a4": {
        "e1": "e1",
        "e2": "e2",
        "e3": 003,
        "e4": 004,
        "e5": null,
        "f1": {
            "g1": 001,
            "g2": 002,
            "g3": 003
        }
    },
    "a5": [
        {
            "h1": "h2",
            "h2": 002,
            "h3": 003,
            "h4": 004,
            "h5": 005,
            "h6": 006,
            "h7": 007,
            "h8": 008,
            "h9": 009,
            "h10": 010,
            "h11": -011,
            "h12": -012,
            "h13": -013
        }
    ],
    "metaInfo": {
        "erstellt": "2016-12-20T10:54:14.459+0000",
        "version": "1"
    }
},

我将这个结构中的18个从“01”变为“18”作为对象名称。所以我从一开始就用这样一个简单的代码开始:

$.getJSON('data.json', function(data) {         
console.log(data);
console.log(data["01"].a5.h1[0]);
});

在控制台中我在第二个日志中出现故障:“未捕获的TypeError:无法读取未定义的属性'a5'”。第一个console.log正确显示了JSON。

那么我的失败在哪里?

2 个答案:

答案 0 :(得分:1)

你正在使用错误的for循环,你应该做像

这样的事情
for(key in data){do something}

答案 1 :(得分:0)

以下是循环对象键值的方法。现在,您可以在表创建中实现此功能。

function drawTable(data) {
              for (var key in data) {
              alert("property  "+key+ " is " + data[key] ); 
    }
    }

如果你只想要非空的elemens,那么试试这个

function drawTable(data) {
       for (var key in data) {
          if (data.hasOwnProperty(key)&& data[key]!==null){

          alert("property  "+key+ " is " + data[key] ); 
   }
  }
 }
相关问题