Home > other >  building json tree from list of file paths
building json tree from list of file paths

Time:09-20

I have list of file paths and need them to be organized in a tree structure like the following.

{
    "label": "VP Accounting",
    "children": [
      {
        "label": "iWay",
        "children": [
          {
            "label": "Universidad de Especialidades del Espíritu Santo"
          },
          {
            "label": "Marmara University"
          },
          {
            "label": "Baghdad College of Pharmacy"
          }
        ]
      },
      {
        "label": "KDB",
        "children": [
          {
            "label": "Latvian University of Agriculture"
          },
          {
            "label": "Dublin Institute of Technology"
          }
        ]
      },

what I did so far is the following

output = {}
current = {}
for path in paths :
    current = output
    for segment in path.split("/") :
        if segment != '':
            if segment not in current:
                current[segment] = {}
            current  = current[segment] 
   

The output is a tree like structure but I can not add the keys ["label", "children"]

CodePudding user response:

The idea is to maintain the dictionary that your code is building as an auxiliary helper structure (which is called helper below, and is simplified to a flat dictionary), and to create the other (desired) structure in parallel (having the lists).

Note that the top level should really be a list as it is not guaranteed all entries will start with the same folder ("segment").

Here is your code adapted to create the children lists and add the labels:

output = []
root = { "children": output }
helper = {}
for path in paths:
    current = root
    subpath = ""
    for segment in path.split("/"):
        if "children" not in current:
            current["children"] = []
        subpath  = "/"   segment
        if subpath not in helper:
            helper[subpath] = { "label": segment }
            current["children"].append(helper[subpath])
        current = helper[subpath]

print(output)
  • Related