2017-01-16 99 views
1

我重新启动了主题:嵌套的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" 
    } 
}, 

我从“01”到“18”中有18个这样的结构作为对象名称。在我上第二个日志故障控制台

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

:所以我从一开始就从一个简单的代码,这样的“遗漏的类型错误:无法读取属性未定义‘A5’”。第一个console.log正确显示了JSON。

那么我的失败在哪里?

+0

什么/哪里出了问题? – Dekel

+1

那个JSON对象不是一个数组;它不会有'.length'。 – Pointy

+0

“我的代码不起作用”。怎么样?出了什么问题?是否报告错误? *什么都会发生? – Pointy

回答

1

您正在使用错误的循环,你应该这样做

for(key in data){do something} 
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]); 
    } 
    } 
}