title: How to resolve a recursive nested tree in jsonb?
body: <p>So I have a flattened tree like this:</p>
  <pre><code>[{
      aid: &quot;id3&quot;
      atype: &quot;&quot;
      data: [&quot;id1&quot;, &quot;id2&quot;]
  },
  
  {
      aid: &quot;id1&quot;
      atype: &quot;&quot;
      data: [&quot;id3&quot;, &quot;id2&quot;]
  },
  
  {
      aid: &quot;id2&quot;
      atype: &quot;&quot;
      bdata: {aid: &quot;id4&quot;, atype: &quot;nested&quot;, data: [&quot;id1&quot;, &quot;id3&quot;]}
      data: []
  }]
  </code></pre>
  <p>I want to gather that tree and resolve ids into data with recursion loops into something like this (say we start from <code>&quot;id3&quot;</code>):</p>
  <pre><code>{
      aid: &quot;id3&quot;
      payload: &quot;1&quot;
      data: [ 
      &quot;id1&quot;:{
          aid: &quot;id1&quot;
          atype: &quot;&quot;
          data: [&quot;id3&quot;:Null, &quot;id2&quot;:Null]
      },
      &quot;id2&quot;:{
              aid: &quot;id2&quot;
              atype: &quot;&quot;
              bdata: {aid: &quot;id4&quot;, atype: &quot;nested&quot;, data: [&quot;id1&quot;:Null, &quot;id3&quot;:Null]}
              data: []
      }]
  }
  </code></pre>
  <p>So that we would get breadth-first search and resolve some field into <code>&quot;value&quot;: &quot;object with that field&quot;</code> on first entrance and <code>&quot;value&quot;: Null</code></p>
  <p>So How can one implement such a list to a tree in Postgres JSONb\ <a href="https://www.postgresql.org/docs/9.5/functions-json.html" rel="nofollow noreferrer">JSON</a>?</p>
  <p>I understand one could do it using something like PL/Python yet I failed to see a PL/Python function example that could do such a thing as not putting all JSON records into ram...</p>
  <pre><code>{'id1': {'aid': 'id1', 'atype': '', 'data': ['id3', 'id2']},
   'id2': {'aid': 'id2',
    'atype': '',
    'bdata': {'aid': 'id4', 'atype': 'nested', 'data': ['id1', 'id3']},
    'data': []},
   'id3': {'aid': 'id3', 'atype': '', 'data': ['id1', 'id2']}}
  </code></pre>
  <p>Is not really usable for me - So I need a real tree.</p>