Method to save networkx graph to json graph?

后端 未结 6 1001
长发绾君心
长发绾君心 2020-12-29 04:38

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 wou

6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 04:49

    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
    

提交回复
热议问题