Alex Rivera | Logout

Convert JSON to HTML Tree

Asked 2009-07-04T20:29:45.850
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",
} ] }
Edit
Report

1 Answer

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;
}
answered 2011-12-30T23:32:24.617

Your Answer