无论如何可以帮助我解析我的示例数据的多级json格式:
[{
"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" }
]}]
到目前为止我有这个代码:
$(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>'; });
这段代码正在解析第二级,我的问题是数据是否超过两个级别。我可以问什么是最好的方法吗?谢谢。
我也尝试了这个帖子中的答案 JSON Recursive looping issue with Jquery
但我无法让它工作。我的目标是将其呈现为 TreeView
修复:感谢 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);
}
});}
最佳答案
您可以使用以下递归函数来解析 UL 和 LI 元素中的数据结构:
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>';
}
关于javascript - 使用jquery进行JSON递归解析,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29118699/