Method to save networkx graph to json graph?

24,752

Solution 1

This documentation contains a full description

A simple example is this:

import networkx as nx
from networkx.readwrite import json_graph

DG = nx.DiGraph()
DG.add_edge('a', 'b')
print json_graph.dumps(DG)

You can also take a look at the Javascript/SVG/D3 nice example on adding physics to the graph visualization.

Solution 2

Generally I use the following code :

import networkx as nx; 
from networkx.readwrite import json_graph;
G = nx.Graph();
G.add_node(...)
G.add_edge(...)
....
json_graph.node_link_data(G)

it will create json formatted graph in which the nodes are in nodes and edges in links in addition to other information about the graph (directionality, ... etc)

Solution 3

Here is a JSON approach that I just did, together with code to read the results back in. It saves the node and edge attributes, in case you need that.

import simplejson as json
import networkx as nx
G = nx.DiGraph()
# add nodes, edges, etc to G ...

def save(G, fname):
    json.dump(dict(nodes=[[n, G.node[n]] for n in G.nodes()],
                   edges=[[u, v, G.edge[u][v]] for u,v in G.edges()]),
              open(fname, 'w'), indent=2)

def load(fname):
    G = nx.DiGraph()
    d = json.load(open(fname))
    G.add_nodes_from(d['nodes'])
    G.add_edges_from(d['edges'])
    return G

Solution 4

The rest of the solutions didn't work for me. From the networkx 2.2 documentation:

nx.write_gpickle(G, "test.gpickle")
G = nx.read_gpickle("test.gpickle")

Solution 5

Try this:

# Save graph
nx.write_gml(G, "path_where_graph_should_be_saved.gml")

# Read graph
G = nx.read_gml('path_to_graph_graph.gml')
Share:
24,752

Related videos on Youtube

Bob
Author by

Bob

Updated on July 09, 2022

Comments

  • Bob
    Bob almost 2 years

    Seems like there should be a method in networkx to export the json graph format, but I don't see it. I imagine this should be easy to do with nx.to_dict_of_dicts(), but would require a bit of manipulation. Anyone know of a simple and elegant solution?

    • fmark
      fmark almost 14 years
      What exactly is the JSON graph format?
    • Bob
      Bob almost 14 years
      basically a list of nodes and adjacencies, but sorta confusing with a simple and an extended version: thejit.org/static/v20/Docs/files/Loader/Loader-js.html
    • Y00
      Y00 over 3 years
      @Bob Hi, do you know, how to read in this from c++ ?
  • Elle Najt
    Elle Najt about 6 years
    This doesn't seem to work anymore. In particular, 'DiGraph' object doesn't have an attribute 'edge.'
  • Nic Scozzaro
    Nic Scozzaro almost 5 years
    AttributeError: module 'networkx.readwrite.json_graph' has no attribute 'dumps'
  • herman
    herman about 4 years
    The link to the example adding physics is broken.