简体   繁体   English

如何将networkx(python)节点序列化为json格式?

[英]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.我有一个 networkx 图,我想通过使用 json 格式的连接发送一个节点(包括它的属性)。 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?有没有办法实现这一目标?

You could call json.dumps() on the node or a tuple of (node,data).您可以在节点或 (node,data) 元组上调用 json.dumps()。 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}]'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM