如何访问用于强制定向的JSON文件中的一个字段?

时间:2014-03-10 17:00:04

标签: javascript json d3.js

我正在开发基于http://bl.ocks.org/mbostock/4062045#index.html的强制网络,但使用以下格式的JSON文件:

{"organizations":[
   {"member":
      {"name":"Green 13",
       "target":"TCAN",
       "category":"community group",
       "source":"G13"}
   }, ....

正如您所看到的,根对象是“组织”,顶级子对象是“成员”。 (JSON文件必须采用这种格式,因为我是从Drupal模块生成的。)

我使用以下代码提取成员数组:

var links=members.organizations.map(function(members) {
    return members.member;
});

网络正常运行,但我无法使用category属性设置圆圈的颜色。

如何在“填充”中使用“类别”,在“文本”中使用“名称”? (目前,“text”使用“source”值。)

1 个答案:

答案 0 :(得分:0)

问题在于您没有将类别放入您正在生成的节点中。为此,请修改生成节点的代码,如下所示:

links.forEach(function(link) {
  link.source = nodes[link.source] || (nodes[link.source] = {name: link.name, category: link.category});
  link.target = nodes[link.target] || (nodes[link.target] = {name: link.name, category: link.category});
});

这将允许您根据类别为节点着色,并添加正确的文本。完整示例here

示例不太有用 - 节点的名称和源/目标字符串不匹配,这会让事情变得混乱。例如,源“G13”不存在(应该是“Green 13”?),也不存在“TRSG”。