Reputation: 337
I am trying to generate JSON file for my graph using below code.
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'))
it's throwing error AttributeError: 'str' object has no attribute 'items'
If I remove the attribute('layer') from my graph I am able to save in JSON format.My aim is to save the graph with attributes. Is this the right way to create JSON using networkx ??
AttributeError Traceback (most recent call last) in ()
8 else:
9 G[node][type] = '2'
---> 10 d = json_graph.node_link_data(G)
11 json.dump(d, open('data.json','w'))
C:\Users\ljose\AppData\Local\Continuum\Anaconda3\lib\site-packages\networkx\readwrite\json_graph\node_link.py in node_link_data(G, attrs)
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' object has no attribute 'items'
Upvotes: 0
Views: 506
Reputation: 2630
The error comes from the fact that G[node][type] = 1
is actually assigning a weight 1
to edge (node, type)
instead of assigning attribute type
to node node
value 1
. The following should fix it:
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[node][type] = '1'
else:
G.node[node][type] = '2'
d = json_graph.node_link_data(G)
Upvotes: 1