Patrick Dully
Patrick Dully

Reputation: 47

Nested JSON cant read property

I Restarted the Topic:

I´m a little bit dumb. The Problem is I showed you just a bit from the JSON cause its a confidential document. The JSON is nested like this example:

"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"
    }
},

I got 18 of this constructions from "01" to "18" as Object name. So i started from the beginning with a simple code like this:

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

in the console i got the failure on second log: "Uncaught TypeError: Cannot read property 'a5' of undefined". The first console.log shows the JSON correctly.

so where is my failure?

Upvotes: 1

Views: 624

Answers (2)

Rafique Ahmed
Rafique Ahmed

Reputation: 117

Here is how you can loop through object key value. Now you can implement this in table creation.

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

If you want only elemens which are not null then try this

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

          alert("property  "+key+ " is " + data[key] ); 
   }
  }
 }

Upvotes: 0

Mitesh Pant
Mitesh Pant

Reputation: 542

You are using wrong for loop you should do something like

for(key in data){do something}

Upvotes: 1

Related Questions