我有一个JSON对象musicianobj,我在下面粘贴了一个例子:
{
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.")
}
}
);}
答案 0 :(得分:2)
你解密了吗?它似乎仍然是一个字符串。
musicianobj = JSON.parse(musicianobj);
console.log(musicianobj.name); // Now this should work
答案 1 :(得分:0)
搞定了!我必须在[0]
之后加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.")
}
}
);}