且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何转换为D3的JSON格式?

更新时间:2023-08-31 21:49:40

没有规定的格式,因为你通常可以通过各种访问函数重新定义你的数据=https://github.com/mbostock/d3/wiki/Hierarchy-Layout#wiki-children =noreferrer> hierarchy.children )和 array.map 。但是你引用的格式可能是树的最方便的表示,因为它使用默认的访问器。

There's no prescribed format, as you can usually redefine your data through various accessor functions (such as hierarchy.children) and array.map. But the format you quoted is probably the most convenient representation for trees because it works with the default accessors.

第一个问题是你打算显示 tree 。对于图形,数据结构按照节点链接。对于树,对布局的输入是根节点,它可能有一个数组子节点,其叶节点具有关联的

The first question is whether you intend to display a graph or a tree. For graphs, the data structure is defined in terms of nodes and links. For trees, the input to the layout is the root node, which may have an array of child nodes, and whose leaf nodes have an associated value.

如果您要显示图表,而且所有的都是边缘列表,那么您将需要以在边缘上迭代,以便产生节点的阵列和链路的阵列。假设您有一个名为graph.csv的文件:

If you want to display a graph, and all you have is a list of edges, then you'll want to iterate over the edges in order to produce an array of nodes and an array of links. Say you had a file called "graph.csv":

source,target
A1,A2
A2,A3
A2,A4

您可以使用 d3.csv ,然后生成一个节点和链接数组:

You could load this file using d3.csv and then produce an array of nodes and links:

d3.csv("graph.csv", function(links) {
  var nodesByName = {};

  // Create nodes for each unique source and target.
  links.forEach(function(link) {
    link.source = nodeByName(link.source);
    link.target = nodeByName(link.target);
  });

  // Extract the array of nodes from the map by name.
  var nodes = d3.values(nodeByName);

  function nodeByName(name) {
    return nodesByName[name] || (nodesByName[name] = {name: name});
  }
});

然后,您可以将这些节点和链接传递到强制布局以显示图形:

You can then pass these nodes and links to the force layout to visualize the graph:

  • http://bl.ocks.org/2949937

如果您想生成做一个稍微不同的数据转换形式,为每个父节点累加子节点。

If you want to produce a tree instead, then you'll need to do a slightly different form of data transformation to accumulate the child nodes for each parent.

d3.csv("graph.csv", function(links) {
  var nodesByName = {};

  // Create nodes for each unique source and target.
  links.forEach(function(link) {
    var parent = link.source = nodeByName(link.source),
        child = link.target = nodeByName(link.target);
    if (parent.children) parent.children.push(child);
    else parent.children = [child];
  });

  // Extract the root node.
  var root = links[0].source;

  function nodeByName(name) {
    return nodesByName[name] || (nodesByName[name] = {name: name});
  }
});

像这样:

  • http://bl.ocks.org/2949981