首页 > 解决方案 > 从python中的嵌套字典创建分层Json

问题描述

我有如下嵌套字典(它是 cosmos gremlin 输出),我想将其转换为 python 中的分层 json。我想在 D3.js 中使用它来创建分层树。你能告诉我如何解决这个问题吗?感谢您的回复。

示例嵌套字典:

{"Root_Level":{"key":"Root_Level","value":{
            "Operation":{
               "key":"Operation",
               "value":{}
            },
            "Technology":{
               "key":"Technology",
               "value":{
                  "Top Management":{
                     "key":"Top Management",
                     "value":{
                        "Associate Product Lead":{
                           "key":"Associate Product Lead",
                           "value":{
                              "Associate Architect":{
                                 "key":"Associate Architect",
                                 "value":{
                                    "Principal Consultant":{
                                       "key":"Principal Consultant",
                                       "value":{}
                                    }}}}}}}}}}}}

预期输出:

{ "name": "Root_Level", "children":[ { "name": "Operation", "children": [] }, { "name": "Technology", "children":[ { "name": "Top Management", "children": [ { "name": "Associate Product Lead" ,"children": [ { "name": "Associate Architect" ,"children": [ {
"name": "Principal Consultant", "children": [] }]}]}]}]}]}

标签: pythonjsond3.jshierarchical-data

解决方案


您可以使用下面的功能来获得您想要的。

result = tree(data)[0][0]必需的,因为第一个元素是您想要的。

def tree(data):
    result = []
    if isinstance(data, dict):
        for v in data.values():
            temp = {'name': v['key']}
            temp['children'] = tree(v['value'])
            result.append(temp)
    return result

data = {"Root_Level":{"key":"Root_Level","value":{ "Operation":{ "key":"Operation", "value":{} }, "Technology":{ "key":"Technology", "value":{ "Top Management":{ "key":"Top Management", "value":{ "Associate Product Lead":{ "key":"Associate Product Lead", "value":{ "Associate Architect":{ "key":"Associate Architect", "value":{ "Principal Consultant":{ "key":"Principal Consultant", "value":{} }}}}}}}}}}}}
result = tree(data)[0]

print(result)

输出

{'name': 'Root_Level',
 'children': [{'name': 'Operation', 'children': []},
              {'name': 'Technology',
               'children': [{'name': 'Top Management',
                             'children': [{'name': 'Associate Product Lead',
                                           'children': [{'name': 'Associate '
                                                                 'Architect',
                                                         'children': [{'name': 'Principal '
                                                                               'Consultant',
                                                                       'children': []}]}]}]}]}]}

推荐阅读