我正在尝试从此 json 文件中提取值,到目前为止我可以在控制台中看到我的对象,但是如何提取要在 d3 中使用的目标值
d3.json "https://api.github.com/repos/wesm/D3py/commits", (data) ->
console.log data[0]
return
这是 json https://api.github.com/repos/wesm/D3py/commits
最终我希望能够使用它来使用这些元素创建 svg 圆,所以我计划将值放入这样的简单列表中......
svg_w = 800
svg_h = 400
padding = 50
svg = d3.select("body").append("svg").attr("width", svg_w).attr("height", svg_h)
list = [
{ "item": 1, "date": "2012-01-04T01:39:42Z", "commit_name": "Mike Dewar", "id":1, "message" : "clenaed up typos in README" },
{ "item": 2, "date": "2012-01-04T01:37:33Z", "commit_name": "Mike Dewar", "id":2, "message" : "updated the README to point people at the v2 branch" },
{ "item": 3, "date": "2011-12-16T03:09:41Z", "commit_name": "Mike Dewar", "id":2, "message" : "added ignore file" },
{ "item": 4, "date": "2011-10-06T12:05:53Z", "commit_name": "Mike Dewar", "id":2, "message" : "merging" },
{ "item": 5, "date": "2011-08-16T20:48:02Z", "commit_name": "Mike Dewar", "id":3, "message" : "added time series" }]
names = (m.item for m in list)
console.log names
nodes = svg.append("g").attr("class", "nodes").selectAll("circle")
.data(names).enter().append("g")
.attr("transform", (d, i) ->
dx = i * 70 + padding
dy = svg_h / 2
"translate(" + dx + "," + dy + ")"
)
nodes.append("circle").attr("class", "node").attr "r", 20
nodes.append("text").attr("text-anchor", "middle").text (d) ->d.name
最佳答案
你尝试过这样的事情吗?
(JS代码)
var list = [],
dataLength = data.length;
for (var i = 0, item; i < dataLength; i++) {
var obj = {};
item = data[i];
// You may need to check here for every property you're gonna access:
// item.commit, item.commit.author, item.commit.message, item.commit.author.date, item.author, item.author.name
if (item && item.commit) {
obj.item = i;
obj.date = item.commit.author.date;
obj['commit_name'] = item.author.name;
// Populate id here based on your logic...
//obj.id = someId;
obj.message = item.commit.message;
// Push newly created obj to list.
list[list.length] = obj;
}
}
关于javascript - 如何使用coffeescript或javascript读取json文件/解析的值以在d3 java脚本中使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21992480/