codegirl
codegirl

Reputation: 387

getting value of nested JSON with jquery

I have very little experience working with jSON

My problem is getting the value from nested arrays.

I've tried for loops and .each() but for some reason it never works as expected.

I'm trying to access the artname.artists.name for each artname object.

I can console.log it by doing console.log(data.artname[0].artists.name);

I've tried to use for loop inside .each();

Can someone help me out here?

Here is a sample of may code

var i;
var actors = data.artname;
var text = "";
for (i=0; i <actors.length; i++){
 text += actors[i] + "<br>";
console.log(actors.name);
}

I can access the role from artname but I'm not able to go deeper and access the actors name from artists

$.each(data.artname, function(i, arts){
$("#arts").append( '<li>' + 'Role:' + arts.role + " " + '</li>');  

   $.each(arts.artists, function(j,actor){ 


     $("#actor").append( '<li>' + 'Actor:' + actor.name  + '</li>'); // gives undefined


   });

});

Here is a part of the JSON file.

    "data": {
"artname" : [ {
    "nr" : 123,
    "role" : "john booth",
    "artists" : {
      "nr" : 81,
      "name" : "Tom Tomson",
      "birthday" : "1954-01-11",
      "allowed" : true,
      "printForm" : "Tom Hanks (11.01.1954-15.04.1999)"
    },
    "profession" : {
      "name" : "actors"
    }
  }, 
  "artname" : [ {
      "nr" : 153,
      "role" : "clair luv",
      "artists" : {
        "nr" : 141,
        "name" : "Ron Ronson",
        "birthday" : "1924-03-11",
        "allowed" : true,
        "printForm" : "Ron Ronsson (11.03.1924-11.04.1959)"
      },
      "profession" : {
        "name" : "actors"
      }
    }, 
    "artname" : [ {
        "nr" : 423,
        "role" : "john booth",
        "artists" : {
          "nr" : 64,
          "name" : "Jane Joe",
          "birthday" : "1974-01-11",
          "allowed" : true,
          "printForm" : "Jane Doe (11.01.1974-15.04.1999)"
        },
        "profession" : {
          "name" : "actors"
        }
      }

}

Upvotes: 0

Views: 49

Answers (1)

Marcus
Marcus

Reputation: 1930

With

$.each(data.artname, function(i, arts){
    $.each(arts.artists, function(j,actor){

you loop over arts.artists. But this is a Object, not a Array. Your variable j will become the key/attribute-name and actor become the value:

$.each(arts.artists, function(j,actor){ 
  console.log(j+': '+actor);
}

try this and rethink what do you want to get instead :)

When you only need the name try this one:

$.each(data.artname, function(i, arts){
    $("#arts").append( '<li>' + 'Role:' + arts.role + " " + '</li>');  
    console.log(arts.artists.name);
});

Upvotes: 1

Related Questions