Note
Click here to download the full example code
JSON ExportΒΆ
This is an example on how to export a graph into JSON format. Our JSON format is very simple and compatible with the sigmajs library.
Start by importing the package.
import jgrapht
from jgrapht.generators import complete_graph
from jgrapht.io.exporters import generate_json
Let us create an undirected graph
g = jgrapht.create_graph(directed=False)
and use the complete generator to populate the graph,
complete_graph(g, 5)
print(g)
Out:
({0, 1, 2, 3, 4}, {0={0,1}, 1={0,2}, 2={0,3}, 3={0,4}, 4={1,2}, 5={1,3}, 6={1,4}, 7={2,3}, 8={2,4}, 9={3,4}})
We will export the graph to string in JSON format.
output = generate_json(g)
print(output)
Out:
{"creator":"JGraphT JSON Exporter","version":"1","nodes":[{"id":"0"},{"id":"1"},{"id":"2"},{"id":"3"},{"id":"4"}],"edges":[{"source":"0","target":"1"},{"source":"0","target":"2"},{"source":"0","target":"3"},{"source":"0","target":"4"},{"source":"1","target":"2"},{"source":"1","target":"3"},{"source":"1","target":"4"},{"source":"2","target":"3"},{"source":"2","target":"4"},{"source":"3","target":"4"}]}
Let us also export the graph using some custom attributes.
vertex_attrs = {}
for v in g.vertices:
vertex_attrs[v] = {}
vertex_attrs[v]['label'] = 'vertex {}'.format(v)
edge_attrs = {}
for e in g.edges:
u, v, _ = g.edge_tuple(e)
edge_attrs[e] = {}
edge_attrs[e]['name'] = 'edge {}-{}'.format(u, v)
Now call the exporter with the vertex and edge attributes dictionaries as extra parameters.
output = generate_json(g, per_vertex_attrs_dict=vertex_attrs, per_edge_attrs_dict=edge_attrs)
print(output)
Out:
{"creator":"JGraphT JSON Exporter","version":"1","nodes":[{"id":"0","label":"vertex 0"},{"id":"1","label":"vertex 1"},{"id":"2","label":"vertex 2"},{"id":"3","label":"vertex 3"},{"id":"4","label":"vertex 4"}],"edges":[{"source":"0","target":"1","name":"edge 0-1"},{"source":"0","target":"2","name":"edge 0-2"},{"source":"0","target":"3","name":"edge 0-3"},{"source":"0","target":"4","name":"edge 0-4"},{"source":"1","target":"2","name":"edge 1-2"},{"source":"1","target":"3","name":"edge 1-3"},{"source":"1","target":"4","name":"edge 1-4"},{"source":"2","target":"3","name":"edge 2-3"},{"source":"2","target":"4","name":"edge 2-4"},{"source":"3","target":"4","name":"edge 3-4"}]}
For an export to file use function jgrapht.io.exporters.write_json()
.
Total running time of the script: ( 0 minutes 0.003 seconds)