我搞乱了last.fm API。我拉着user's top artists data,它返回一个像这样的JSON:d3.js:嵌套数据 - 键返回undefined的所有数据
{ "artist": [
{
"name": "Kanye West",
"playcount": "282",
"mbid": "164f0d73-1234-4e2c-8743-d77bf2191051",
"url": "http:\/\/www.last.fm\/music\/Kanye+West",
"streamable": "0",
"@attr": {
"rank": "1"
}
},
{
"name": "Childish Gambino",
"playcount": "148",
"mbid": "7fb57fba-a6ef-44c2-abab-2fa3bdee607e",
"url": "http:\/\/www.last.fm\/music\/Childish+Gambino",
"streamable": "0",
"@attr": {
"rank": "2"
}
},
等。经过一番小提琴之后,我为第二个JSON(例如摇滚,流行音乐,嘻哈)拉动了第二个JSON,循环播放每位艺术家,并将他们最受欢迎的标签推送到原始数据集。所以,现在我的JSON的样子:
{ "artist": [
{
"name": "Kanye West",
"playcount": "282",
"mbid": "164f0d73-1234-4e2c-8743-d77bf2191051",
"url": "http:\/\/www.last.fm\/music\/Kanye+West",
"streamable": "0",
"@attr": {
"rank": "1"
},
"tag": "hip hop",
},
{
"name": "Childish Gambino",
"playcount": "148",
"mbid": "7fb57fba-a6ef-44c2-abab-2fa3bdee607e",
"url": "http:\/\/www.last.fm\/music\/Childish+Gambino",
"streamable": "0",
"@attr": {
"rank": "2"
},
"tag": "hip hop",
},
我想要做的下一件事是使用d3.nest
使用每个标签(流派)为重点,以卷起我的数据。我正在关注这个tutorial。我的最终目标是制作一个sunburst,与内圈的流派(例如,你听多少嘻哈,独立歌曲,流行音乐?)和 - 也许点击 - 每个艺术家你听多少(例如Kanye West对幼稚甘比诺)。
的主要问题是在这里:
var dataset = d3.nest()
.key(function(d) {
return d.tag;
})
.entries(topArtists);
的key
将返回undefined
所有数据点。当我尝试其他可能的密钥(d.name
,d.streamable
)时,它们工作正常。我的数据按需要卷起来。所以这与tag
有关 - 这是我推送到topArtists
数据集的对象。我不确定发生了什么事。下面是我通过循环如何,并结合标签信息,艺术家信息:
//Merge
topArtists.forEach(function(d) {
//loop through each of the top 10 artists selected
//pull their mbid (musicbrainz id) and plug it into the var for tags
tags = 'http://ws.audioscrobbler.com/2.0/?method=artist.gettoptags&mbid='+ d.mbid + '&api_key=[my api key]&format=json';
//pull that JSON
d3.json(tags, function(error, tag) {
if (error) { return console.log(error); };
//capture only the most commonly used tag (artistTag)
//and also clean it up a bit
artistTag = tag.toptags.tag[0].name.toLowerCase().split('-').join(' ');
//push that string value to the original JSON
d["tag"] = artistTag;
}); // close tags JSON call
}); //close topArtists loop
关闭这些循环后,如果我console.log(topArtists)
,这一切看起来很好 - 标签已被添加。 JSFiddle here。
问题是'd3.json'是异步的。它在'forEach'循环结束后运行。你可能想考虑一下[queue.js](https://github.com/mbostock/queue)。 – 2014-11-08 11:27:26
谢谢,拉尔斯。我认为它可能是异步的 - 但是当我运行'forEach'循环和第二个JSON调用的'console.log(topArtists)* *外部时,它看起来很好 - 所有的'tags'都被追加。如果在下一行中,我尝试'd3.nest' - 它们会变成未定义的。事实上,即使我做了'd3.nest().key(function(d){console.log(topArtists);})',标签也显示出来了。由于某种原因,它们只是没有被卷起来。 – 2014-11-08 12:58:52
所以'console.log()'打印一个对象不完全正确吗?在中,你点击它来展开属性等。点击的时间实际上是在评估时。也就是说,当你打印表达式时,它不在那里,但是当你点击它时,就是这样。在将数据放入数据之前和之后,您可以通过两次打印相同的表达式来查看。当您检查控制台上的这些对象时,即使它们在打印时明显不同,它们也是一样的。 – 2014-11-08 13:09:58