0

I have a parent child pair from table, example:

links=(("Tom","Dick"),
       ("Dick","Harry"),
       ("Tom","Larry"),
       ("Bob","Leroy"),
       ("Bob","Earl"),
       ("Earl","Joy"), 
       ("Joy","Joy child"), 
       ("Joy","Joy child2"),
       ("Joy child2", "Maria"))

and I am trying to create jstree from this pairs. I went through various links but cant get this tuple to work. Can anyone please provide a recursive function in python which takes the tuple as mentioned above or any combination of parent-child-grand-child pairs as input and creates a hierarchy by creating a json similar to this format

{
     "name": "Tom",
     "children": [
         {
             "name": "Dick"
         }
     ] 
}

Thank you in Advance:) I really appreciate your help!

Alex Lisovoy
  • 5,767
  • 3
  • 27
  • 28
yash
  • 11
  • 6
  • What have you tried so far? See [how to ask a good question.](http://stackoverflow.com/help/how-to-ask) – agold Nov 24 '15 at 16:36
  • @agold I tried this link functions: http://stackoverflow.com/questions/18025130/recursively-build-hierarchical-json-tree-in-python – yash Nov 24 '15 at 16:48
  • What is wrong with [this answer](http://stackoverflow.com/a/18025360/1771479)? – agold Nov 24 '15 at 16:50
  • @agold , When I executed the function in second answer, it only generates first level parent child nodes and the other pairs are not seen in the json. Also, the correct answer does not give all the parent child nodes in the json. – yash Nov 24 '15 at 16:58
  • @agold, Its my bad, yes the function in the link is working fine. Thank you for your help. I am closing this story now. – yash Nov 24 '15 at 17:40
  • http://stackoverflow.com/questions/18025130/recursively-build-hierarchical-json-tree-in-python – yash Nov 24 '15 at 17:43

1 Answers1

0
import json

links = (("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Tom","Hurbert"),("Tom","Neil"),("Bob","Leroy"),("Bob","Earl"),("Tom","Reginald"))

name_to_node = {}
root = {'name': 'Root', 'children': []}
for parent, child in links:
    parent_node = name_to_node.get(parent)
    if not parent_node:
        name_to_node[parent] = parent_node = {'name': parent}
        root['children'].append(parent_node)
    name_to_node[child] = child_node = {'name': child}
    parent_node.setdefault('children', []).append(child_node)

print json.dumps(root, indent=4)
devav2
  • 367
  • 1
  • 7
  • 19