我正在尝试使用下面的代码为我的图形生成JSON文件 .
G = nx.DiGraph()
G.add_nodes_from(['A', 'B', 'C', 'D'])
G.add_edges_from([('A', 'B'), ('B', 'C'), ('B', 'D')])
type = 'layer'
for node in G.nodes():
if node in ('A', 'B'):
G[node][type] = '1'
else:
G[node][type] = '2'
d = json_graph.node_link_data(G)
json.dump(d, open('data.json','w'))
这是投掷错误 AttributeError: 'str' object has no attribute 'items'
如果我从图表中删除属性('layer'),我可以保存为JSON格式 . 我的目标是使用属性保存图形 . 这是使用networkx创建JSON的正确方法吗?
更新:无法在评论中添加整个错误,因此在main中添加 .
()中的AttributeError Traceback(最近一次调用最后一次)
8 else:
9 G[node][type] = '2'
---> 10 d = json_graph.node_link_data(G)
11 json.dump(d, open('data.json','w'))
node:link_data(G,attrs)中的C:\ Users \ ljose \ AppData \ Local \ Continuum \ Anaconda3 \ lib \ site-packages \ networkx \ readwrite \ json_graph \ node_link.py
90 dict(chain(d.items(),
91 [(source, mapping[u]), (target, mapping[v])]))
---> 92 for u, v, d in G.edges_iter(data=True)]
93
94 return data
C:\ Users \ ljose \ AppData \ Local \ Continuum \ Anaconda3 \ lib \ site-packages \ networkx \ readwrite \ json_graph \ node_link.py in . ( . 0)
90 dict(chain(d.items(),
91 [(source, mapping[u]), (target, mapping[v])]))
---> 92 for u, v, d in G.edges_iter(data=True)]
93
94 return data
AttributeError:'str'对象没有属性'items'
1 回答
该错误来自于
G[node][type] = 1
实际上将权重1
分配给边(node, type)
而不是将属性type
分配给节点node
值1
. 以下应该解决它: