Reputation: 437
anyway can help me to parse the multilevel json format my sample data is:
[{
"name":"mainparentid:20 ","id":"161","icon":"null","parentId":"0","spaceId":"1","status":"null",
"children":
[
{"name":"Home","id":"166","parentId":"161","spaceId":"1","status":"NEW",
"children":[{
"name":"TV","id":"167","parentId":"166","spaceId":"1","status":"NEW",
"children":[{
"name":"testtt","id":"177","parentId":"167","spaceId":"1","status":"NEW"
}]
}]
},{"name":"Office 1","id":"164","parentId":"161","spaceId":"1","status":"NEW" }
]}]
so far i have this code:
$(data).each(function(index){
var flevel = eval(this.children)
$(flevel).each(function(i){
//print the first level records
itms += '<ul>'+
itms += '<li>'+this.name+'<ul>';
if(typeof this.children !== 'undefined'){
var slevel = eval(this.children);
$(slevel).each(function(i){
itms += '<li>'+this.name+'</li>'
});
//and so on and so fort to print
}
});
itms += '</ul></li></ul>'; });
this code is working upto second level of parsing my problem is if the data is more than two levels. Can i ask what is the best way to do this. Thank you.
I also tried the answer in this thread JSON Recursive looping issue with Jquery
but i can't make it to work. My goal is to render this as a treeview
FIXES: thank you to Mouser
$(data).each(function(index){
var flevel = this.children
$(flevel).each(function(i){
//print the first level records
if(typeof this.children !== 'undefined'){
var slevel = this.children;
$(slevel).each(function(i){
recursive(slevel);
});
}
});});
function recursive(data){
$(data).each(function(i){
if(has a children){
recursive(this.children);
}
});}
Upvotes: 0
Views: 1046
Reputation: 416
Try this code snippet for the tree view structure you want
$(data).each(function (index) {
var flevel = eval(this.children)
$(flevel).each(function (i) {
//print the first level records
itms += '<ul>';
itms += '<li>' + this.name + '<ul>';
var child = this.children;
var itmend = '</ul></li>';
while (child != undefined) {
debugger
itms = iterateChildren(child, itms)
child = child[0].children;
itmend += '</ul></li>';
}
itms += itmend;
});
itms += '</ul></li></ul>';
});
function iterateChildren(child, itms) {
if (child[0].children == undefined) {
itms += '<li>' + child[0].name + '</li>'
}
else {
itms += '<li>' + child[0].name + '<ul>'
}
return itms;
}
Upvotes: 0
Reputation: 41
You can use following recursive function to parse your data structure in UL and LI elements:
function ParseChildren(data)
{
var result = '<ul>';
for (var i=0; i< data.length; i++)
{
result += '<li>' + data[i].name + '</li>';
if (data[i].children && data[i].children.length > 0)
result += ParseChildren(data[i].children);
}
return result + '</ul>';
}
Upvotes: 3