Q:

Print networkx DiGraph to Nested JSON format

I have a networkx DiGraph. 
>> G = nx.DiGraph()
>> G.add_edges_from(product([0],[1,2])) # product is itertools.product 
>> G.add_edges_from(product([1],[3,4])) 

The graph looks like this inside: 
>> G.adj  
 {0: {1: {}, 2: {}},  
  1: {3: {}, 4: {}},  
  2: {},  
  3: {},  
  4: {}} 

I would like this to be printed to a json format like the following: 
{   
    name: 0,
    children: [ 
        {
            name: 1,
            children: [
                {
                    name: 3,
                    children: [] 
                }, 
                {
                    name: 4,
                    children: []
                }
                ]
        }, 
        {
            name: 2,
            children:[]
        }
    ]
} 

(The reason being, I am trying to write it in a format that this D3 visualization takes in. https://gist.github.com/mbostock/4063550)
I am not sure how to go about this. Any help much appreciated. 
thanks. 

A:

You can use json_graph.tree_data() to output the data in a nested format.
From the documentation
from networkx.readwrite import json_graph
import networkx as nx
import json
G = nx.DiGraph([(1,2)])
data = json_graph.tree_data(G,root=1)
s = json.dumps(data)

Which gives {"id": 1, "children": [{"id": 2}]}

