13

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",
} ] }

7 Answers 7

8
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.

7
  • It's also missing adding the li into the ul. Add a ul.appendChild(li) before the for-loop closes and it should work. Jul 4, 2009 at 20:50
  • 1
    There is also a problem with validity: The Title of the UL is just appended to it. This is something that is not quite useful.
    – Boldewyn
    Jul 5, 2009 at 9:11
  • arent u passing forward a new ul every single instance of recursion? dont you need to append all of these the root obj thats passed in initially??
    – oldboy
    Nov 7, 2019 at 6:01
  • arent you passing forward a brand new ul on every single instance of recursion? dont you need to append everything to the same ul??
    – oldboy
    Nov 7, 2019 at 9:04
  • The idea was to have a tree-like structure, i.e. nested uls for the nested JSON structure. So, having a new ul for every descent into the next level is required. The “deeper” uls are appended to lis, which themselves are then appended to the ul one level up.
    – Boldewyn
    Nov 7, 2019 at 16:15
7

I had a problem getting my browser to accept the data structure submitted by the OP, but here is a fully working example I've drawn up for my own, similar purposes. Beside the function I provide the data structure as well, with name/branches instead of title/folder.

function to_ul(branches) {
  var ul = document.createElement("ul");

  for (var i = 0, n = branches.length; i < n; i++) {
    var branch = branches[i];
    var li = document.createElement("li");

    var text = document.createTextNode(branch.name);
    li.appendChild(text);

    if (branch.branches) {
      li.appendChild(to_ul(branch.branches));
    }

    ul.appendChild(li);
  }

  return ul;
}

function renderTree() {
  var treeEl = document.getElementById("tree");

  var treeObj = {
    "root": [{
      "name": "George & Sarah Trede",
      "branches": [{
        "name": "George & Frances Trede",
        "branches": [{
          "name": "Mary (Trede) Jempty"
        }, {
          "name": "Carol (Trede) Moeller"
        }]
      }, {
        "name": "Mary (Trede) Sheehan"
      }, {
        "name": "Ward Trede"
      }]
    }]
  };

  treeEl.appendChild(to_ul(treeObj.root));
}

renderTree()
<div id="tree"></div>

3

I've used PURE with some success in the past for this kind of thing.

3
function to_li(obj, name) {
    var li = document.createElement("li");
    if (typeof(name) != "undefined") {
        var strong = document.createElement("strong");
        strong.appendChild(document.createTextNode(name + ": "));
        li.appendChild(strong);
    }
    if (typeof(obj) != "object"){
        li.appendChild(document.createTextNode(obj));
    } else {
        var ul = document.createElement ("ul");
        for (var prop in obj){
            ul.appendChild(to_li(obj[prop],prop));
        }
        li.appendChild(ul);
    }
    return li;
}
2

Check out the jquery plugin JSON2HTML, it's a little simpler to use than PURE and I've used it on a couple of site's I've created.

http://json2html.com

0
0

@Boldewyn: I believe you can also use a For...In loop instead of a regular For loop to shorten the code a bit. Of course, I don't have much experience using this kind of loop, so please check my code snippet.

for (var i in obj.folder) {
    li = document.createElement ("li");
    li.appendChild (document.createTextNode (i.title));
    // if the child has a 'folder' prop on its own, call me again
    if (i.folder) {
      li.appendChild (to_ul (i.folder));
    }
}
1
  • Nope, took it out again. The i would contain the range 0..n and not the array items.
    – Boldewyn
    Jul 5, 2009 at 10:23
0

I have made a pip package for the same do check it out JSON2tree. Install it using pip install json2tree then use cli tool to create HTML tree. json2tree -j example.json -o output.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.