Skip to content Skip to sidebar Skip to footer

Custom Json Formatting In Python

I have the following code to generate json representation of list of lists. Levels=[['L1','L1','L2'], ['L1','L1','L3'], ['L1','L2'], ['L2','L2','L3'],

Solution 1:

root={}
Levels=[['L1','L1','L2'],
        ['L1','L1','L3'],
        ['L1','L2'],
        ['L2','L2','L3'],
        ['L2','L2','L1'],
        ['L3','L2'],
        ['L4','L2','L1'],
        ['L4','L2','L4']]

def append_path(root, paths):
    if paths:
        child = root.setdefault(paths[0], {})
        append_path(child, paths[1:])

for p in Levels:
    append_path(root, p)

def convert(d):
    templist=[]
    noofchildren=0
    if(len(d.items())==0):
        return ([{}],1)
    for k,v in d.items():
        temp,children=convert(v)
        noofchildren+=children
        if(temp):
            templist.append({"name":k+"("+str(children)+")",'children':temp})
        else:
            templist.append({'name': k+"("+str(children)+")", 'children':[{}]})

    return (templist,noofchildren)    

# Print results
import json
print(json.dumps(convert(root)[0],  indent=2))

OUTPUT

[
  {
    "name": "L1(3)",
    "children": [
      {
        "name": "L1(2)",
        "children": [
          {
            "name": "L2(1)",
            "children": [
              {}
            ]
          },
          {
            "name": "L3(1)",
            "children": [
              {}
            ]
          }
        ]
      },
      {
        "name": "L2(1)",
        "children": [
          {}
        ]
      }
    ]
  },
  {
    "name": "L2(2)",
    "children": [
      {
        "name": "L2(2)",
        "children": [
          {
            "name": "L3(1)",
            "children": [
              {}
            ]
          },
          {
            "name": "L1(1)",
            "children": [
              {}
            ]
          }
        ]
      }
    ]
  },
  {
    "name": "L3(1)",
    "children": [
      {
        "name": "L2(1)",
        "children": [
          {}
        ]
      }
    ]
  },
  {
    "name": "L4(2)",
    "children": [
      {
        "name": "L2(2)",
        "children": [
          {
            "name": "L1(1)",
            "children": [
              {}
            ]
          },
          {
            "name": "L4(1)",
            "children": [
              {}
            ]
          }
        ]
      }
    ]
  }
]

Post a Comment for "Custom Json Formatting In Python"