Converting a parent child relationship into Json in python
Question: I have a list of list like the below. The first column is the parent, second
is the child, and the third are node attributes. I need to convert the below
to a JSON format like the following.

    
    
    0 0 "flair" 1000
    0 1 "analytics" 1000
    
    1 2 "cluster" 1000
    2 3 "AgglomerativeCluster" 1000
    2 4 "CommunityStructure" 1000
    
    1 5 "Graph" 1000
    5 6 "BetweennessCentrality" 1000
    5 7 "LinkDistance"
    

* * *
    
    
    pc = []
    pc.append([0, 0 ,"flair", 1000])
    pc.append([0,1, "analytics", 1000])
    pc.append([1, 2, "cluster", 1000])
    pc.append([2 ,3, "AgglomerativeCluster", 1000])
    pc.append([2 ,4, "CommunityStructure" ,1000])
    pc.append([1 ,5, "Graph", 1000])
    pc.append([5, 6, "BetweennessCentrality", 1000])
    pc.append([5, 7, "LinkDistance",1000])
    
    {
     "name": "flare",
     "children": [
      {
       "name": "analytics",
       "children": [
        {
         "name": "cluster",
         "children": [
          {"name": "AgglomerativeCluster", "size": 3938},
          {"name": "CommunityStructure", "size": 3812},
         ]
        },
        {
         "name": "graph",
         "children": [
          {"name": "BetweennessCentrality", "size": 3534},
          {"name": "LinkDistance", "size": 5731}
         ]
        }
       ]
      }
     ]
    }
    


Answer: A little change to your input, for a root node "flair", I use '-1' as its
parent id instead of '0'.

    
    
    import json
    pc = []
    pc.append([-1, 0 ,"flair", 1000])
    pc.append([0,1, "analytics", 1000])
    pc.append([1, 2, "cluster", 1000])
    pc.append([2 ,3, "AgglomerativeCluster", 1000])
    pc.append([2 ,4, "CommunityStructure" ,1000])
    pc.append([1 ,5, "Graph", 1000])
    pc.append([5, 6, "BetweennessCentrality", 1000])
    pc.append([5, 7, "LinkDistance",1000])
    
    def listToDict(input):
        root = {}
        lookup = {}
        for parent_id, id, name, attr in input:
            if parent_id == -1: 
                root['name'] = name;
                lookup[id] = root
            else:
                node = {'name': name}
                lookup[parent_id].setdefault('children', []).append(node)
                lookup[id] = node
        return root
    
    result = listToDict(pc)
    print result
    print json.dumps(result)
    

