Sorting JSON object(s) into a Hierarchy

后端 未结 4 973
感情败类
感情败类 2021-01-06 10:57

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\",
         


        
4条回答
  •  自闭症患者
    2021-01-06 11:54

    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]
    

提交回复
热议问题