Skip to content Skip to sidebar Skip to footer

How To Use JQuery To Render A JSON Tree As Nested HTML Using Divs?

I am looking for a way to render a JSON tree using nested
as mentioned in the title. Here is a sample of the data (there is a max of 8 levels in the tree): { 'child

Solution 1:

You could do this in raw JS with little to no difficulty:

function json2html(json) {
    var i, ret = "";
    ret += "<ul>";
    for( i in json) {
        ret += "<li>"+i+": ";
        if( typeof json[i] === "object") ret += json2html(json[i]);
        else ret += json[i];
        ret += "</li>";
    }
    ret += "</ul>";
    return ret;
}

Just call that function with your object, and it will return the HTML as a set of nested lists - you can of course change it to use just <div>s if you prefer.

EDIT: And here's a version that uses DOM elements and returns a node that can be inserted with appendChild or similar:

function json2html(json) {
    var i, ret = document.createElement('ul'), li;
    for( i in json) {
        li = ret.appendChild(document.createElement('li'));
        li.appendChild(document.createTextNode(i+": "));
        if( typeof json[i] === "object") li.appendChild(json2html(json[i]));
        else li.firstChild.nodeValue += json[i];
    }
    return ret;
}

Post a Comment for "How To Use JQuery To Render A JSON Tree As Nested HTML Using Divs?"