Convert JSON to HTML Tree

javascript, json

Solution

function to_ul (obj) {
  // --------v create an <ul> element
  var f, li, ul = document.createElement ("ul");
  // --v loop through its children
  for (f = 0; f < obj.folder.length; f++) {
    li = document.createElement ("li");
    li.appendChild (document.createTextNode (obj.folder[f].title));
    // if the child has a 'folder' prop on its own, call me again
    if (obj.folder[f].folder) {
      li.appendChild (to_ul (obj.folder[f].folder));
    }
    ul.appendChild (li);
  }
  return ul;
}

Caveat: No error checking! If a 'title' or 'folder' is missing, the whole thing could blow up.

Problem

I would like to generate an HTML tree (preferably UL-LI) from the JSON example below. Does anyone have a simple, recursive JS function (not a framework) that can handle this specific structure? Thanks for your help! ``` { "folder" : [ { "title" : "1", "folder" : [ { "title" : "1.1", "folder" : [ { "title" : "1.1.1", } , { "title" : "1.1.2", } ] } ] } , { "title" : "2", } ] } ```

Original source