title: Recursively build hierarchical JSON tree?
body: <p>I have a database of parent-child connections.  The data look like the following but could be presented in whichever way you want (dictionaries, list of lists, JSON, etc). </p>
  
  <pre><code>links=(("Tom","Dick"),("Dick","Harry"),("Tom","Larry"),("Bob","Leroy"),("Bob","Earl"))
  </code></pre>
  
  <p>The output that I need is a hierarchical JSON tree, which will be rendered with d3.  There are discrete sub-trees in the data, which I will attach to a root node. So I need to recursively go though the links, and build up the tree structure. The furthest I can get is to iterate through all the people and append their children, but I can't figure out to do the higher order links (e.g. how to append a person with children to the child of someone else). This is similar to another question <a href="https://stackoverflow.com/questions/10737273/recursive-function-to-create-hierarchical-json-object">here</a>, but I have no way to know the root nodes in advance, so I can't implement the accepted solution. </p>
  
  <p>I am going for the following tree structure from my example data.</p>
  
  <pre><code>{
  "name":"Root",
  "children":[
      {
       "name":"Tom",
       "children":[
           {
           "name":"Dick",
           "children":[
               {"name":"Harry"}
           ]
           },
           {
            "name":"Larry"}
       ]
      },
      {
      "name":"Bob",
      "children":[
          {
          "name":"Leroy"
          },
          {
          "name":"Earl"
          }
      ]
      }
  ]
  }
  </code></pre>
  
  <p>This structure renders like this in my d3 layout.  <img src="https://i.stack.imgur.com/1Acgc.png" alt="Rendered image"></p>