2012-11-23 252 views
0

的孩子我有一個JSON對象musicianobj,其中我已經粘貼下面的例子:無法訪問JSON對象

{ 
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.") 
    } 
    } 
);} 
+2

你是否解碼它從JSON之前戳它呢? – Zirak

+0

嘗試:console.log(typeof musicianobj); – luin

+1

向我們展示一些代碼! – Eric

回答

2

你解碼了嗎?看起來它仍然是一個字符串。

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

害怕它沒有工作,我得到了'Uncaught SyntaxError:意外的令牌o'。據我所知,Facebook SDK返回JSON對象而不是字符串,因爲標準的JSON訪問起作用。實際上,該對象是從Facebook sdk返回的對象中獲取的,使用代碼var musicianobj = trackdata.data.musician; –

0

明白了!我必須在musicianobj之後加上[0]。顯然,我不太瞭解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.") 
    } 
    } 
);}