简体   繁体   English

将 Python Dict 转换为 jqtree 结构

[英]Convert Python Dict to jqtree structure

In one of my projects I am trying to convert the following python dict在我的一个项目中,我试图转换以下 python dict

{
'node1' : 
    {
        'child1': {}, 
        'child2':{}
     }, 
'node2': {'child3': {}
    }
}

to the following structure,到以下结构,

var data = [
{
    name: 'node1',
    children: [
        { name: 'child1' },
        { name: 'child2' }
    ]
},
{
    name: 'node2',
    children: [
        { name: 'child3' }
    ]
}
];

This format is used by jqtree . jqtree使用此格式。 Can anyone suggest the best way for this.任何人都可以建议最好的方法。 Since the result data structure does not contain 'node1' as key, I am not sure how to insert next level data into it.由于结果数据结构不包含“node1”作为键,我不确定如何将下一级数据插入其中。

Here's a quick recursive function that will work for your example.这是一个适用于您的示例的快速递归函数。 If the children contain other types (lists, etc.) instead of purely being a nested-dict structure, you may need to make some modifications:如果子项包含其他类型(列表等)而不是纯粹的嵌套字典结构,您可能需要进行一些修改:

def jqtree_from(data):
  jq = []
  for key, value in data.items():
    node = {'name': key}
    if value:
      node['children'] = jqtree_from(value)
    jq.append(node)
  return jq

Example:例子:

>>> d = # your example here
>>> jqtree_from(d)
[{'name': 'node1', 
  'children': [{'name': 'child1'}, 
               {'name': 'child2'}]}, 
 {'name': 'node2', 'children': [{'name': 'child3'}]}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM