Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <pre><code>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 </code></pre> <p>Output (with indentation added by me):</p> <pre><code>[ { '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' } ] </code></pre> <p>It also works with items that are nested more than one deep. Example input:</p> <pre><code>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" }, ] </code></pre> <p>Output:</p> <pre><code>[ { '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' } ] } ] } ] } ] </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload