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

我有这个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":{}
                        }
                }
            }
        }
    }
}


有谁可以帮助我吗?

最佳答案

无需递归。试试看(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": {}
                    }
                }
            }
        }
    }
}


因此,一次传递数据以将“指针”替换为实际的子代,然后再次传递以除去名称。所有词典/列表都在适当的位置进行了变异,因此链接起来的孩子继续工作。

10-06 06:22