marcel marcel - 26 days ago 9
Javascript Question

How to access nested JSON object key and values

I am trying to access the key and values of my nested array like this:

var obj = $.getJSON("mydata.json", function() {
console.log( "load success" );
});

Object.keys(obj[2].type).forEach(function(key) {
console.log(key, obj[key]);
});


But I get an error.

Here's the structure of the JSON file:

{
"nodes": [
{
"nd": "nd1",
"cat": "cat1"
}
],
"links": [
{
"id": 100
}
],
"types": [
{
"type": "one",
"image": "image001"
},
{
"type": "two",
"image": "image002"
},
{
"type": "three",
"image": "image003"
}
]


}

My goal is to get a list of values of:


one two three

Answer

Something like that?

You have to firstly acces to object.types attribute, then iterate on it to retrieve every type.

var object = {
  "nodes": [{
    "nd": "nd1",
    "cat": "cat1"
  }],
  "links": [{
    "id": 100
  }],
  "types": [{
    "type": "one",
    "image": "image001"
  }, {
    "type": "two",
    "image": "image002"
  }, {
    "type": "three",
    "image": "image003"
  }]
};


function parseJson(object){
    object.types.forEach(function(key) {
      console.log(key.type);
    });
}

parseJson(object);

--- update to anwer question in comment ---

you could enclose the code in a function, and call it when you load your json:

$.getJSON("mydata.json", function(data) {
    parseJson(data);
});