myJson = [
{
"name":"Folder 2",
"id":"zRDg",
"parent":"OY00",
"type":"folder"
},
{
"name":"Folder 1",
"id":"OY00",
"type":"folder"
},
{
"name":"Folder 3",
"id":"ZDE1",
"type":"folder"
},
{
"name":"DX00025.jpg",
"id":"9Xdd",
"parent":"OY00",
"type":"jpeg"
}
]
#this creates a dictionary that maps id names to JSON items.
#ex. itemsKeyedById["9Xdd"] gives the jpg item with id "9Xdd"
itemsKeyedById = {i["id"]: i for i in myJson}
#iterate through each item in the `myJson` list.
for item in myJson:
#does the item have a parent?
if "parent" in item:
#get the parent item
parent = itemsKeyedById[item["parent"]]
#if the parent item doesn't have a "children" member,
#we must create one.
if "children" not in parent:
parent["children"] = []
#add the item to its parent's "children" list.
parent["children"].append(item)
#filter out any item that has a parent.
#They don't need to appear at the top level,
#since they will appear underneath another item elsewhere.
topLevelItems = [item for item in myJson if "parent" not in item]
print topLevelItems
输出(我添加了缩进):
[
{
'name': 'Folder 1',
'id': 'OY00',
'type': 'folder',
'children': [
{
'name': 'Folder 2',
'id': 'zRDg',
'parent': 'OY00',
'type': 'folder'
},
{
'name': 'DX00025.jpg',
'id': '9Xdd',
'parent': 'OY00',
'type': 'jpeg'
}
]
},
{
'name': 'Folder 3',
'id': 'ZDE1',
'type': 'folder'
}
]
它也适用于嵌套超过一层的项目。示例输入:
myJson = [
{
"name":"TopLevel folder",
"id":"0",
"type":"folder",
},
{
"name":"MidLevel folder",
"id":"1",
"type":"folder",
"parent":"0"
},
{
"name":"Bottom Level folder",
"id":"2",
"type":"folder",
"parent":"1"
},
{
"name":"Vacation Picture",
"id":"3",
"type":"jpg",
"parent":"2"
},
]
输出:
[
{
'type': 'folder',
'name': 'TopLevel folder',
'id': '0',
'children': [
{
'type': 'folder',
'name': 'MidLevel folder',
'parent': '0',
'id': '1',
'children': [
{
'type': 'folder',
'name': 'Bottom Level folder',
'parent': '1',
'id': '2',
'children': [
{
'type': 'jpg',
'name': 'Vacation Picture',
'parent': '2',
'id': '3'
}
]
}
]
}
]
}
]