python中如何解析图形链接json

2024-04-25 08:02:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想构建一个基于按钮的聊天机器人,我已经使用networkx创建了一个图形链接json。但我无法解析它。我希望json格式是嵌套格式,比如父级和子级。但这并没有给我属性。请帮帮我。 我使用下面的代码得到下面的响应。你知道吗

代码:

import json
import networkx as nx
from networkx.readwrite import json_graph
DG = nx.DiGraph()
DG.add_node(1)
DG.add_node(2)
DG.add_edges_from([(1,3, {'button': 'yes'}),(3,4, {'button': 'no'})])
DG.add_edges_from([(4,5,{'button': 'yes'}),(4,6)])
DG.add_edge(1,2)
data = json.dumps(json_graph.node_link_data(DG))

响应:

{"directed": true, "multigraph": false, "graph": {}, "nodes": [{"id": 1}, {"id": 2}, {"id": 3}, {"id": 4}, {"id": 5}, {"id": 6}], "links": [{"button": "yes", "source": 1, "target": 3}, {"source": 1, "target": 2}, {"button": "no", "source": 3, "target": 4}, {"button": "yes", "source": 4, "target": 5}, {"source": 4, "target": 6}]}

我尝试获取类似树的json响应,但它没有属性值。你知道吗

代码:

json_graph.tree_data(DG,root=1)

响应:

{'id': 1, 'children': [{'id': 3, 'children': [{'id': 4, 'children': [{'id': 5}, {'id': 6}]}]}, {'id': 2}]}

预期输出:

{'id': 1, 'children': [{'id': 3, "button": "yes",'children': [{'id': 4,"button": "no", 'children': [{'id': 5,"button": "yes"}, {'id': 6,"button": "no"}]}]}, {'id': 2,"button": "no"}]}

我想要像上面提到的json中的button这样的属性,这样我就可以轻松地解析它。你知道吗


Tags: no代码importnetworkxaddidjsonsource

热门问题