0

I need to sort out a JSON array into a Hierarchy, here my JSON file never orderd but follow structure:

{
  "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"
}

Into this:

{
  "name":"Folder 1",
  "id":"OY00",
  "type":"folder",
  "children": [{
    "name":"Folder 2",
    "id":"zRDg",
    "type":"folder"
    },
    {
    "name":"DX00025.jpg",
    "id":"9Xdd",
    "type":"jpeg"
  }]
},
{
    "name":"Folder 3",
    "id":"ZDE1",
    "type":"folder"
}

I can't really figure it out, as i'm new to python, my start(wrong):

for index,item in result:
    if item['parent']:
        for item2 in result:
            if item2['id'] == item['parent']:
                item['children'] = item2
                brake 

This is ok, but the problem is it not correct python, folder1/folder/folder3/ wont work for this, i need a recursive function

Kivylius
  • 6,357
  • 11
  • 44
  • 71

1 Answers1

1

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]
MostafaR
  • 3,547
  • 1
  • 17
  • 24
  • Can you copy pase it to this thread and i will award you 150 points and you deserve it. http://stackoverflow.com/questions/15544581/sorting-json-objects-into-a-hierarchy Also delete this post, thank you. – Kivylius Mar 26 '13 at 12:34