1
# Copyright (C) 2011 by
2
# Aric Hagberg <hagberg@lanl.gov>
3
# Dan Schult <dschult@colgate.edu>
4
# Pieter Swart <swart@lanl.gov>
7
from itertools import count,repeat
10
__author__ = """Aric Hagberg (hagberg@lanl.gov))"""
11
__all__ = ['node_link_data', 'node_link_graph']
13
def node_link_data(G):
14
"""Return data in node-link format that is suitable for JSON serialization
15
and use in Javascript documents.
24
A dictionary with node-link formatted data.
28
>>> from networkx.readwrite import json_graph
29
>>> G = nx.Graph([(1,2)])
30
>>> data = json_graph.node_link_data(G)
32
To serialize with json
35
>>> s = json.dumps(data)
39
Graph, node, and link attributes are stored in this format but keys
40
for attributes must be strings if you want to serialize with JSON.
44
node_link_graph, adjacency_data, tree_data
46
mapping = dict(zip(G,count()))
48
data['directed'] = G.is_directed()
49
data['multigraph'] = G.is_multigraph()
50
data['graph'] = list(G.graph.items())
51
data['nodes'] = [ dict(id=n, **G.node[n]) for n in G ]
52
data['links'] = [ dict(source=mapping[u], target=mapping[v], **d)
53
for u,v,d in G.edges(data=True) ]
56
def node_link_graph(data, directed=False, multigraph=True):
57
"""Return graph from node-link data format.
62
node-link formatted graph data
65
If True, and direction not specified in data, return a directed graph.
68
If True, and multigraph not specified in data, return a multigraph.
73
A NetworkX graph object
77
>>> from networkx.readwrite import json_graph
78
>>> G = nx.Graph([(1,2)])
79
>>> data = json_graph.node_link_data(G)
80
>>> H = json_graph.node_link_graph(data)
84
node_link_data, adjacency_data, tree_data
86
multigraph = data.get('multigraph',multigraph)
87
directed = data.get('directed',directed)
89
graph = nx.MultiGraph()
93
graph = graph.to_directed()
95
graph.graph = dict(data.get('graph',[]))
97
for d in data['nodes']:
98
node = d.get('id',next(c))
100
nodedata = dict((str(k),v) for k,v in d.items() if k!='id')
101
graph.add_node(node, **nodedata)
102
for d in data['links']:
103
source = d.pop('source')
104
target = d.pop('target')
105
edgedata = dict((str(k),v) for k,v in d.items()
106
if k!='source' and k!='target')
107
graph.add_edge(mapping[source],mapping[target],**edgedata)