title: How to Create a JSON Tree from a Tabulated Hierarchy in Python
body: <p>I'm sure there's an elegant way of doing this in Python (or at a push, Javascript), but for the life of me I can't see it...</p>
  
  <p>I have a CSV file of the form:</p>
  
  <pre><code>ID, Name, Description
  A, A-name,
  A100, A100-name, A100-desc
  A110, A110-name, A110-desc
  A111, A111-name, A111-desc
  A112, A112-name, A112-desc
  A113, A113-name, A113-desc
  A120, A120-name, A120-desc
  A131, A131-name, A131-desc
  A200, A200-name, A200-desc
  B, B-name,
  B100, B100-name, B100-desc
  B130, B130-name, B130-desc
  B131, B131-name, B131-desc
  B140, B140-name, B140-desc
  </code></pre>
  
  <p>and I want to generate a hierarchical JSON structure so I can visualise the data in <a href="http://thejit.org/static/v20/Docs/files/Loader/Loader-js.html" rel="nofollow">theJIT</a>.</p>
  
  <pre><code>var json = {  
    "id": "aUniqueIdentifier",  
    "name": "usually a nodes name",  
    "data": {  
      "some key": "some value",  
      "some other key": "some other value"  
     },  
    "children": [ *other nodes or empty* ]  
  }; 
  </code></pre>
  
  <p>My plan was to map ID to id, Name to name, Description to data.desc, and organise the hierarchy so that:</p>
  
  <ul>
  <li>Root is parent of A and B</li>
  <li>A is parent of A100 and A200</li>
  <li>A100 is parent of A110 and A120</li>
  <li>A110 is parent of A111, A112 and A113</li>
  <li>B is parent of B100</li>
  <li>B100 is parent of B130 and B140</li>
  <li>B130 is parent of B131</li>
  </ul>
  
  <p>There is also a pathological case in the otherwise regular ordering by ID, where A100 is parent of A131 (the expected A130 is not present).</p>
  
  <p>I was hoping to find an elegant Python solution to this, but it's defeating me at the moment, even ignoring the pathological case...</p>