如何将JSON数据转换为树图像? [英] How to convert JSON data into a tree image?

查看:497
本文介绍了如何将JSON数据转换为树图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 treelib 生成树,现在我需要轻松地-读取树木的版本,所以我想将它们转换为图像.例如:

I'm using treelib to generate trees, now I need easy-to-read version of trees, so I want to convert them into images. For example:

以下树的示例JSON数据:

The sample JSON data, for the following tree:

有数据:

>>> 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}}]}}

无数据:

>>> print(tree.to_json(with_data=False))
{"Harry": {"children": ["Bill", {"Jane": {"children": [{"Diane": {"children": ["Mary"]}}, "Mark"]}}]}}

无论如何都可以使用 graphviz

Is there anyway to use graphviz or d3.js or some other python library to generate tree using this JSON data?

推荐答案

对于这样的树,不需要使用库:您可以直接生成Graphviz DOT语言语句.唯一棘手的部分是从JSON数据提取树边缘.为此,我们首先将JSON字符串转换回Python dict,然后递归解析该dict.

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 dict, and then parse that dict recursively.

如果树字典中的名称没有子代,则为简单字符串,否则为字典,我们需要扫描其"children"列表中的项目.我们发现的每个(父母,孩子)对都将附加到全局列表edges.

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 "children" list. Each (parent, child) pair we find gets appended to a global list edges.

这行有点神秘:

name = next(iter(treedict.keys()))

treedict获取单个密钥.这就是我们的名字,因为这是treedict中的唯一键.在Python 2中,我们可以做到

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

name = treedict.keys()[0]

,但先前的代码在Python 2和Python 3中均可使用.

but the previous code works in both Python 2 and Python 3.

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 & print to stderr so we can verify 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} -> {1};'.format(*row))
print('}')

stderr输出

{
    "Harry": {
        "children": [
            "Bill",
            {
                "Jane": {
                    "children": [
                        {
                            "Diane": {
                                "children": [
                                    "Mary"
                                ]
                            }
                        },
                        "Mark"
                    ]
                }
            }
        ]
    }
}

标准输出

strict digraph tree {
    Harry -> Bill;
    Harry -> Jane;
    Jane -> Diane;
    Diane -> Mary;
    Jane -> Mark;
}

以上代码在Python 2& Python3.它将JSON数据打印到stderr,因此我们可以验证其正确性.然后将Graphviz数据打印到stdout,以便我们可以将其捕获到文件中或直接将其通过管道传输到Graphviz程序.例如,如果脚本的名称为"tree_to_graph.py",则可以在命令行中执行此操作,以将图形另存为名为"tree.png"的PNG文件:

The code above runs on Python 2 & 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":

python tree_to_graph.py | dot -Tpng -otree.png

这是PNG输出:

这篇关于如何将JSON数据转换为树图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆