Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serialize networkx (python) node to json format?

I have a networkx graph, and I would like to send a node (including its attributes) through a connection using json format. I know how to serialize the whole graph:

import networkx as nx
from networkx.readwrite import json_graph
G=nx.Graph()
G.add_node(1)
G.node[1]["name"]="alice"
G.add_node(2)
G.add_edge(1,2)
print json.dumps(json_graph.node_link_data(G))

However, I didn't find a way to serialize a single node, something like

print json.dumps(json_graph.node_data(G.node[1]))

Is there a way to achieve this?

like image 568
Shaharg Avatar asked May 24 '26 18:05

Shaharg


1 Answers

You could call json.dumps() on the node or a tuple of (node,data). The same would work for edges. For example:

In [1]: import networkx as nx

In [2]: G=nx.Graph()

In [3]: G.add_node(1,color='red',size=75)

In [4]: G.add_node(2,color='blue',size=33)

In [5]: import json

In [6]: json.dumps(G.nodes(data=True))  # all nodes
Out[6]: '[[1, {"color": "red", "size": 75}], [2, {"color": "blue", "size": 33}]]'

In [7]: json.dumps((1,G.node[1])) # (node, data) tuple
Out[7]: '[1, {"color": "red", "size": 75}]'
like image 167
Aric Avatar answered May 26 '26 08:05

Aric



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!