1

我有一个 JSON 对象音乐家obj,我在下面粘贴了一个示例:

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

我使用 Javascript SDK 从 Facebook API 得到了这个。我可以运行console.log(musicianobj);它成功地将对象打印到 Chrome 中的日志,但是console.log(musicianobj.name);,console.log(musicianobj[1]);console.log(musicianobj["name"]);所有返回 undefined 都没有明显的原因。有任何想法吗?

编辑:下面的代码。

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.")
    }
    }
  );}
4

2 回答 2

2

你解码了吗?它似乎仍然是一个字符串。

musicianobj = JSON.parse(musicianobj);
console.log(musicianobj.name); // Now this should work
于 2012-11-23T20:15:46.657 回答
0

得到它的工作!我不得不放一个[0]after musicianobj。显然我并不像我想的那样了解 JSON。工作代码粘贴在下面:

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.")
  }
  }
);}
于 2012-11-24T13:54:33.330 回答