嵌套python字典

时间:2013-02-05 11:53:32

标签: python json dictionary

大家好,我正在为此工作几个小时,但似乎我无法完成这项工作。

我有这个json结构:

{
    "1": {
        "name": "foo",
        "color": "black",
        "children": ["2", "3"]
     },
    "2": {
        "name": "foo2",
        "color": "green",
        "children": []
     },
    "3": {
        "name": "foo3",
        "color": "yellow",
        "children": ["4"]
     },
    "4": {
        "name": "foo4",
        "color": "purple",
        "children": []
     }
}

我希望使用python字典在下一个json结构中转换它:

{
    "foo":{
        "color":"black",
        "children":{
            "foo2":{
                "color":"green",
                "children":{}
            },
            "foo3":{ 
                "color":"yellow",
                "children":{
                    "foo4":{
                        "color":"purple", 
                        "children":{}
                        }
                }
            }
        }
    }
}
有人可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

不需要递归。试试这个(s是原始字符串):

>>> import json
>>> data = json.loads(s)
>>> for v in data.values():
    v['children'] = {data[c]['name']:data[c] for c in v['children']}


>>> d = {data['1']['name']:data['1']}
>>> for v in data.values():
    del v['name']


>>> print(json.dumps(d, indent=4))
{
    "foo": {
        "color": "black", 
        "children": {
            "foo2": {
                "color": "green", 
                "children": {}
            }, 
            "foo3": {
                "color": "yellow", 
                "children": {
                    "foo4": {
                        "color": "purple", 
                        "children": {}
                    }
                }
            }
        }
    }
}

因此,一个传递数据以将'指针'替换为实际的子节点,然后第二个传递去除名称。所有词典/列表都已发生变异,以便链接的孩子继续工作。

答案 1 :(得分:0)

首先,你必须知道dict没有被命令,所以你不能知道“1”将是你在迭代时得到的第一把钥匙。 如果始终“1”是第一个元素,那么:

dict_to_convert = {
    "1": {
        "name": "foo",
        "color": "black",
        "children": ["2", "3"]
    },
    "2": {
        "name": "foo2",
        "color": "green",
        "children": []
    },
    "3": {
        "name": "foo3",
        "color": "yellow",
        "children": ["4"]
    },
    "4": {
        "name": "foo4",
        "color": "purple",
        "children": []
    }
}


def convert_dict(dict_to_convert, key=None):
    if key is not None:
        new_dict = {}
        for key in dict_to_convert[key]["children"]:
            new_dict[dict_to_convert[key]["name"]] = {}
            new_dict[dict_to_convert[key]["name"]]["color"] = dict_to_convert[key]["color"]
            new_dict[dict_to_convert[key]["name"]]["children"] = convert_dict(dict_to_convert, key)
    else:
        new_dict = {}
        new_dict[dict_to_convert["1"]["name"]] = {}
        new_dict[dict_to_convert["1"]["name"]]["color"] = dict_to_convert["1"]["color"]
        new_dict[dict_to_convert["1"]["name"]]["children"] = convert_dict(dict_to_convert, "1")
    return new_dict


converted_dict = convert_dict(dict_to_convert)
print converted_dict

我查了一下,确实有效。