I have a follow-up question to Method to save networkx graph to json graph?, but Stack Overflow wouldn't let me add a comment to the answer by Sirus that I would like to clarify, so here's my question.
What is the best way to write the JSON data to a text file?
I'm trying to do the obvious step of writing a file of my json_graph generated by NetworkX so I can read it into D3.js. I can print it to the console with no problem, so I can verify that it works to create the appropriate JSON data. But my attempts to save it to a file have failed and (as usual with Python) the documentation is basically worthless. Here's what I tried:
with open('networkdata1.json', 'w') as outfile1:
outfile1.write(json_graph.node_link_data(G))
and it gives me the error: "TypeError: expected a character buffer object" If I run the same code with a simple character string instead of the json graph, then it works perfectly. The problem is with the translation of the json object to text, and I don't know how to do that, and I can't find any examples that include this step. I'm sure it's simple once you know it, but if you don't know Python it's really hard to figure these things out from the material available online.
What is the best way to write the JSON data to a text file? If this IS the correct method, what might else be causing this problem?
Jamie was on the right track, and a partial answer was also on the NetworkX page, combining them creates a working solution:
with open('networkdata1.json', 'w') as outfile1:
outfile1.write(json.dumps(json_graph.node_link_data(G)))
It turns out that it is necessary to convert the graph to a json_graph, and then dump the json to text, and then write that text to a text file. Obviously they should have included that step more obviously in the documentation, but hopefully the next person who starts on this path can find this easy solution here quickly and easily.
Make sure you have import json and import networkx as nx for this to work (although the latter doesn't seem to actually appear in this code snippet).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With