Recursively build tree for json output