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

I am looking for a way to render a JSON tree using nested <div> as indicated in the header. Here is an example of data (there are a maximum of 8 levels in the tree):

 { "children": { "Bacteria": { "children":{ "Verrucomicrobia":{ "children":{ "Methylacidiphilae":{ "children":{ "Methylacidiphilales":{ "children":{}, "count":2, "level":"order", "name":"Methylacidiphilales", "score":1.46 } }, "count":2, "level":"class", "name":"Methylacidiphilae", "score":1.46 } }, "count":2, "level":"phylum", "name":"Verrucomicrobia", "score":1.46 } }, "count":2, "level":"kingdom", "name":"Bacteria", "score":1.46 } }, "count":0, "level":"root", "name":"Root", "score":0.0 } 

I can get / parse the JSON tree and save it in a variable. Now I need to cross the tree recursively and either:

  • Make each node what can be displayed as HTML.
  • Create a new div node and add a new tree.

But how?

+5
source share
1 answer

You can do this in raw JS with little 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 this function with your object, and it will return the HTML as a set of nested lists - you can, of course, change it to use only the <div> if you want.

EDIT: And here is the version that uses the DOM elements and returns a node that can be inserted using 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; } 
+11
source

All Articles