javascript - 使用jquery进行JSON递归解析

标签 javascript jquery json recursion

无论如何可以帮助我解析我的示例数据的多级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/

相关文章:

jquery - 从函数设置 div 宽度

json - 如何创建具有不同类型值的 Json 对象?

javascript - 点击链接时如何切换图像?

javascript - 根据用户文本输入更新 url 链接并在 Wordpress 中保存更改

javascript - 如何在 document.getelementById 中尝试 null.value

java - JSON转java对象不同属性

arrays - 如何将命名列表转换为对象数组

javascript - 在 Jquery 中渲染图像抛出 500(内部服务器错误)

javascript - 隐藏和显示 :before thru Jquery or better solution?

javascript - 在声明 css 类或 html div 时使用变量