Hugh Rawlinson
Hugh Rawlinson

Reputation: 989

Cannot access children of JSON object

I have a JSON object musicianobj, an example of which I have pasted below:

{
id: "451026389391"
name: "John Frusciante"
type: "profile"
url: "http://open.spotify.com/artist/XXXXXXXXXXXXXX"
}

I got this from the Facebook API using the Javascript SDK. I can run console.log(musicianobj); which successfully prints the object to the log in Chrome, but console.log(musicianobj.name);, console.log(musicianobj[1]);, and console.log(musicianobj["name"]); all return undefined for no apparent reason. Any ideas?

Edit: code below.

var playFriendsTrack = function(friend){
  FB.api("/"+friend+"/music.listens", function(data) {
    var songname = data.data[0].data.song.title;
    var artistname = "";
    FB.api(data.data[0].data.song.id,function(trackdata){
      var musicianobj = trackdata.data.musician;
      console.log(musicianobj);
      console.log(musicianobj["name"]); // Doesn't work
      console.log(musicianobj.name); // Doesn't work
      artistname = musicianobj[1]; // Doesn't work
    });
    if(artistname.length <= 0){
      alert("Error! Please try another friend.")
    }
    }
  );}

Upvotes: 1

Views: 1731

Answers (2)

Hugh Rawlinson
Hugh Rawlinson

Reputation: 989

Got it working! I had to put a [0] after musicianobj. Apparently I don't know JSON as much as I'd like to. The working code is pasted below:

var playFriendsTrack = function(friend){
FB.api("/"+friend+"/music.listens", function(data) {
  var songname = data.data[0].data.song.title;
  var artistname = "";
  FB.api(data.data[0].data.song.id,function(trackdata){
    var musicianobj = trackdata.data.musician;
    console.log(musicianobj);
    console.log(musicianobj[0]["name"]);
    console.log(musicianobj[0].name);
    artistname = musicianobj[0].name;
  });
  if(artistname.length <= 0){
    alert("Error! Please try another friend.")
  }
  }
);}

Upvotes: 0

Sergey Eremin
Sergey Eremin

Reputation: 11080

Have you decoded it? It seems it is still a string.

musicianobj = JSON.parse(musicianobj);
console.log(musicianobj.name); // Now this should work

Upvotes: 2

Related Questions