title: Storing Tree Structures in JSON
body: <p>I'm trying to write a system where the client (browser-based) requests a tree to be returned from the server (app engine, but that's irrelevant). The problem is in converting the tree to JSON: because each object refers to the objects 'below' it, when stringified I end up with an extremely long string which, on parsing, creates new objects for each child instead of references to other nodes.</p>
  
  <p>My current solution would be to write an 'equalTo' and 'toString' function (converting object references to strings) stringify the resulting array and then recreate it on the client side by resolving strings to objects. That solution is making my terrible-algorithm-senses tingle, though, there must be a better way to return such structures through JSON!</p>
  
  <p>EDIT: it just occurred to me that object references could also be converted to array indexes. It's a better solution, but still has that niggling bad-code feel to it.</p>
  
  <p>EDIT2: Right, so I suppose some pseudo-code is in order, then.</p>
  
  <pre><code>var node = {
      children : null;
  };
  
  var root = Object.create(node);
  
  var level1a = Object.create(node);
  var level1b = Object.create(node);
  var level2a = Object.create(node);
  var level2b = Object.create(node);
  
  root.children = [level1a, level1b];
  level1a.children = [level2a, level2b];
  </code></pre>
  
  <p>So you end up with a tree that looks like this:
  <a href="http://i55.tinypic.com/2ch4y0j.jpg" rel="nofollow">stackoverflow won't let me post images</a></p>