显示带递归的JSON响应

时间:2014-07-12 07:35:36

标签: jquery json recursion

我构建了一个JQuery函数,它试图显示从服务器返回的JSON对象的所有内容。目前,我正在使用迭代方法(通过循环遍历每个节点),但我正在尝试应用递归。请提供一些建议。

$.ajax({
    url: url,
    dataType: "json",
    contentType: "application/json",
    success: function (response) {
        for (var key1 in response) {
            var post1 = response[key1];
            console.log(key1 + ": " + post1);
            for (var key2 in post1) {
                //debugger Object[0]
                var post2 = post1[key2];
                console.log(key2 + ": " + post2);
                for (var key3 in post2) {
                    //etc
                }
            }
        }
    }
});

1 个答案:

答案 0 :(得分:1)

将控制台代码分解为一个简单的递归函数并传递" root"反对它。类似的东西:

function dumpIt(obj){
    for (var key1 in obj) {
        var post1 = obj[key1];
        console.log(key1 + ": " + post1);
        // Go recursive on each child object
        dumpIt(post1);
    }
}

$.ajax({
    url: url,
    dataType: "json",
    contentType: "application/json",
    success: function (response) {
        dumpIt(response);
    }
});

稍微强大的版本 - 带缩进:

function dumpIt(obj, indent) {
    if (typeof obj == "object") {
        for (var key1 in obj) {
            var post1 = obj[key1];
            console.log(indent + key1 + ": " + post1);
            // Go recursive on each child object
            dumpIt(post1, indent + " ");
        }
    }
}

请致电:dumpIt(obj, "");

示例JSFiddle:http://jsfiddle.net/TrueBlueAussie/r9PYm/2/