如何将点图转换为json图?

时间:2016-10-26 12:33:23

标签: graphviz dot

我想使用sigma.js来显示一些DOT图。但似乎sigma.js只支持json图形格式。

是否有一些bash工具或javascript模块可以将DOT图转换为json图?

例如来自DOT图:



graph {
 n1 [Label = "n1"];
 n2 [Label = "n2"];
 n3 [Label = "n3"];
 n1 -- n2;
 n1 -- n3;
 n2 -- n2;
}




转移到JSON图:



{
  "nodes": [
    {
      "id": "n0",
      "label": "A node",
      "x": 0,
      "y": 0,
      "size": 3
    },
    {
      "id": "n1",
      "label": "Another node",
      "x": 3,
      "y": 1,
      "size": 2
    },
    {
      "id": "n2",
      "label": "And a last one",
      "x": 1,
      "y": 3,
      "size": 1
    }
  ],
  "edges": [
    {
      "id": "e0",
      "source": "n0",
      "target": "n1"
    },
    {
      "id": "e1",
      "source": "n1",
      "target": "n2"
    },
    {
      "id": "e2",
      "source": "n2",
      "target": "n0"
    }
  ]
}




3 个答案:

答案 0 :(得分:2)

如果您可以使用python并安装2个软件包(networkxpygraphviz),这里有一个将点图转换为json图的简短脚本:

# dot_to_json_graph.py
# http://stackoverflow.com/questions/40262441/how-to-transform-a-dot-graph-to-json-graph

# Packages needed  :
# sudo aptitude install python-networkx python-pygraphviz
#
# Syntax :
# python dot_to_json_graph.py graph.dot

import networkx as nx
from networkx.readwrite import json_graph

import sys

if len(sys.argv)==1:
  sys.stderr.write("Syntax : python %s dot_file\n" % sys.argv[0])
else:
  dot_graph = nx.read_dot(sys.argv[1])
  print json_graph.dumps(dot_graph)

这是你的例子,转换为json图:

  

{"定向":false,"图":[["节点",{"标签":"& #34;}],[" graph",   {" file":" test.dot"}],[" edge",{}],[" name",&#34 ;"]],"节点":[{" id":   " n1","标签":" n1"},{" id":" n2",&#34 ;标签":" n2"},{" id":" n3",   "标签":" n3"}],"链接":[{"来源":0,"目标" :1," key":0},   {" source":0," target":2," key":0},{" source":1,&#34 ;目标":1,   " key":0}]," multigraph":true}

答案 1 :(得分:1)

我无法在Windows和Linux中安装pygraphviz,而且我最近遇到了同样的问题。 networkx现在支持更容易地转储到json中,包括d3.js格式(info in this page

我有两个解决方法:

1-使用PyDot

很快就会过时!由于我们在python中有graphviz接口,因此PyDot可能不会频繁使用。

def dot_to_json(file_in):
    import networkx
    from networkx.readwrite import json_graph
    import pydot
    graph_netx = networkx.drawing.nx_pydot.read_dot(file_in)
    graph_json = json_graph.node_link_data( graph_netx )
    return json_graph.node_link_data(graph_netx)


2-使用graphviz来源

如graphviz界面文档的this part所示,您可以从.dot源文件创建图表。

答案 2 :(得分:0)

dot -Txdot_json -ogrpaph.json graph.dot

请参见https://www.graphviz.org/doc/info/output.html#a:xdot_json