How to use jQuery to render a JSON tree as nested HTML using divs?

前端 未结 1 1262
故里飘歌
故里飘歌 2020-12-30 14:29

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
1条回答
  •  一整个雨季
    2020-12-30 15:04

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

    function json2html(json) {
        var i, ret = "";
        ret += "
      "; for( i in json) { ret += "
    • "+i+": "; if( typeof json[i] === "object") ret += json2html(json[i]); else ret += json[i]; ret += "
    • "; } ret += "
    "; 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

    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;
    }
    

    0 讨论(0)
提交回复
热议问题