How to convert JSON data into a tree image?
<p>I'm using <a href="http://treelib.readthedocs.io/en/latest/examples.html" rel="nofollow">treelib</a> to generate trees, now I need easy-to-read version of trees, so I want to convert them into images. For example:
<a href="https://i.stack.imgur.com/sr9eC.png" rel="nofollow"><img src="https://i.stack.imgur.com/sr9eC.png" alt="enter image description here"></a></p>

<p>The sample JSON data, for the following tree:</p>

<p><a href="https://i.stack.imgur.com/oaR1K.png" rel="nofollow"><img src="https://i.stack.imgur.com/oaR1K.png" alt="enter image description here"></a></p>

<p>With data:</p>

<pre><code>&gt;&gt;&gt; print(tree.to_json(with_data=True))
{"Harry": {"data": null, "children": [{"Bill": {"data": null}}, {"Jane": {"data": null, "children": [{"Diane": {"data": null}}, {"Mark": {"data": null}}]}}, {"Mary": {"data": null}}]}}
</code></pre>

<p>Without data:</p>

<pre><code>&gt;&gt;&gt; print(tree.to_json(with_data=False))
{"Harry": {"children": ["Bill", {"Jane": {"children": [{"Diane": {"children": ["Mary"]}}, "Mark"]}}]}}
</code></pre>

<p>Is there anyway to use <a href="https://pypi.python.org/pypi/graphviz" rel="nofollow">graphviz</a> or <a href="https://d3js.org/" rel="nofollow">d3.js</a> or some other python library to generate tree using this JSON data?</p>

<p>For a tree like this there's no need to use a library: you can generate the Graphviz DOT language statements directly. The only tricky part is extracting the tree edges from the JSON data. To do that, we first convert the JSON string back into a Python <code>dict</code>, and then parse that <code>dict</code> recursively.</p>

<p>If a name in the tree dict has no children it's a simple string, otherwise, it's a dict and we need to scan the items in its <code>"children"</code> list. Each (parent, child) pair we find gets appended to a global list <code>edges</code>.</p>

<p>This somewhat cryptic line:</p>

<pre><code>name = next(iter(treedict.keys()))
</code></pre>

<p>gets a single key from <code>treedict</code>. This gives us the person's name, since that's the only key in <code>treedict</code>. In Python 2 we could do</p>

<pre><code>name = treedict.keys()[0]
</code></pre>

<p>but the previous code works in both Python 2 and Python 3.</p>

<pre><code>from __future__ import print_function
import json
import sys

# Tree in JSON format
s = '{"Harry": {"children": ["Bill", {"Jane": {"children": [{"Diane": {"children": ["Mary"]}}, "Mark"]}}]}}'

# Convert JSON tree to a Python dict
data = json.loads(s)

# Convert back to JSON &amp; print to stderr so we can verfiy that the tree is correct.
print(json.dumps(data, indent=4), file=sys.stderr)

# Extract tree edges from the dict
edges = []

def get_edges(treedict, parent=None):
    name = next(iter(treedict.keys()))
    if parent is not None:
        edges.append((parent, name))
    for item in treedict[name]["children"]:
        if isinstance(item, dict):
            get_edges(item, parent=name)
        else:
            edges.append((name, item))

get_edges(data)

# Dump edge list in Graphviz DOT format
print('strict digraph tree {')
for row in edges:
    print('    {0} -&gt; {1};'.format(*row))
print('}')
</code></pre>

<p><strong>stderr output</strong></p>

<pre class="lang-none prettyprint-override"><code>{
    "Harry": {
        "children": [
            "Bill",
            {
                "Jane": {
                    "children": [
                        {
                            "Diane": {
                                "children": [
                                    "Mary"
                                ]
                            }
                        },
                        "Mark"
                    ]
                }
            }
        ]
    }
}
</code></pre>

<p><strong>stdout output</strong></p>

<pre class="lang-none prettyprint-override"><code>strict digraph tree {
    Harry -&gt; Bill;
    Harry -&gt; Jane;
    Jane -&gt; Diane;
    Diane -&gt; Mary;
    Jane -&gt; Mark;
}
</code></pre>

<p>The code above runs on Python 2 &amp; Python 3. It prints the JSON data to stderr so we can verify that it's correct. It then prints the Graphviz data to stdout so we can capture it to a file or pipe it directly to a Graphviz program. Eg, if the script is name "tree_to_graph.py", then you can do this in the command line to save the graph as a PNG file named "tree.png":</p>

<pre class="lang-bash prettyprint-override"><code>python tree_to_graph.py | dot -Tpng -otree.png
</code></pre>

<p>And here's the PNG output:</p>

<p><img src="https://i.stack.imgur.com/zFvic.png" alt="Tree made by Graphviz" title="Tree made by Graphviz"></p>

python json tree