简体   繁体   中英

Convert Python Dict to jqtree structure

In one of my projects I am trying to convert the following 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 . 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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