我从桌子上有一对父子对, 例如:
links=(("Tom","Dick"),
("Dick","Harry"),
("Tom","Larry"),
("Bob","Leroy"),
("Bob","Earl"),
("Earl","Joy"),
("Joy","Joy child"),
("Joy","Joy child2"),
("Joy child2", "Maria"))
我试图从这对中创建jstree。我经历了各种各样的链接,但不能让这个元组工作。任何人都可以在python中提供一个递归函数,它将上面提到的元组或父子 - 子 - 子对的任意组合作为输入,并通过创建类似于这种格式的json来创建层次结构
{
"name": "Tom",
"children": [
{
"name": "Dick"
}
]
}
先谢谢你:)我真的很感谢你的帮助!
答案 0 :(得分:0)
import json
links = (("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Tom","Hurbert"),("Tom","Neil"),("Bob","Leroy"),("Bob","Earl"),("Tom","Reginald"))
name_to_node = {}
root = {'name': 'Root', 'children': []}
for parent, child in links:
parent_node = name_to_node.get(parent)
if not parent_node:
name_to_node[parent] = parent_node = {'name': parent}
root['children'].append(parent_node)
name_to_node[child] = child_node = {'name': child}
parent_node.setdefault('children', []).append(child_node)
print json.dumps(root, indent=4)