I need to sort out a JSON array into a Hierarchy, here my JSON file, it\'s never ordered but follow structure:
{
\"name\":\"Folder 2\",
\"id\":\"zRDg\",
My solution for this case is something like this:
data = INPUT_LIST
class Item:
def __init__(self, _id, name, type, parent):
self._id = _id
self.name = name
self.type = type
self.parent = parent
self.children = []
def get_dict(self):
return {
'id': self._id,
'name': self.name,
'type': self.type,
'children': [child.get_dict() for child in self.children]
}
lookup = dict((item['id'], Item(item['id'], item['name'], item['type'], item['parent'] if 'parent' in item else None)) for item in data)
root = []
for _id, item in lookup.items():
if not item.parent:
root.append(item)
else:
lookup[item.parent].children.append(item)
dict_result = [item.get_dict() for item in root]