Warning

This documents an unmaintained version of NetworkX. Please upgrade to a maintained version and see the current NetworkX documentation.

networkx.readwrite.json_graph.tree_data

tree_data(G, root, attrs={'children': 'children', 'id': 'id'})[source]

Returns data in tree format that is suitable for JSON serialization and use in Javascript documents.

Parameters
  • G (NetworkX graph) – G must be an oriented tree

  • root (node) – The root of the tree

  • attrs (dict) – A dictionary that contains two keys ‘id’ and ‘children’. The corresponding values provide the attribute names for storing NetworkX-internal graph data. The values should be unique. Default value: dict(id='id', children='children').

    If some user-defined graph data use these attribute names as data keys, they may be silently dropped.

Returns

data – A dictionary with node-link formatted data.

Return type

dict

Raises

NetworkXError – If values in attrs are not unique.

Examples

>>> from networkx.readwrite import json_graph
>>> G = nx.DiGraph([(1,2)])
>>> data = json_graph.tree_data(G,root=1)

To serialize with json

>>> import json
>>> s = json.dumps(data)

Notes

Node attributes are stored in this format but keys for attributes must be strings if you want to serialize with JSON.

Graph and edge attributes are not stored.

The default value of attrs will be changed in a future release of NetworkX.