Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

read json graph networkx file

I'm writing a networkx graph by using this Python function:

from networkx.readwrite import json_graph
def save_json(filename,graph):
    g = graph
    g_json = json_graph.node_link_data(g)
    json.dump(g_json,open(filename,'w'),indent=2)

and was trying to load the graph using:

def read_json_file(filename):
    graph = json_graph.loads(open(filename))
    return graph

where the read function was taken from here.

My problem is that is gives me the error:

AttributeError: 'module' object has no attribute 'load'

which makes sense, since from the networkx documentation there is no load method.

So, my question is how to I load a json file that contains a networkx graph?

like image 329
Miguel Avatar asked Jan 07 '16 20:01

Miguel


1 Answers

given what the official docs say, I think you are looking for something like

def read_json_file(filename):
    with open(filename) as f:
        js_graph = json.load(f)
    return json_graph.node_link_graph(js_graph)

i.e. since the json file is written using json.dump, then use json.load to read the contents back.

Then create the graph from the loaded dictionary.

Note: I have never used the json_graph package so I ignore what the correct options may be in order to recreate your specific type of graph. You might want to go through them in the docs, there appear to be quite a few.

like image 146
Pynchia Avatar answered Nov 06 '22 06:11

Pynchia