javascript - 使用 JavaScript 遍历 JSON 对象树的所有节点

我想遍历 JSON 对象树,但找不到任何库。看起来并不难,但感觉就像在重新发明轮子。

在 XML 中有很多教程展示了如何使用 DOM 遍历 XML 树 :(

最佳答案

如果你认为 jQuery 对于这样一个原始任务来说有点矫枉过正,你可以这样做:

//your object
var o = { 
    foo:"bar",
    arr:[1,2,3],
    subo: {
        foo2:"bar2"
    }
};

//called with every property and its value
function process(key,value) {
    console.log(key + " : "+value);
}

function traverse(o,func) {
    for (var i in o) {
        func.apply(this,[i,o[i]]);  
        if (o[i] !== null && typeof(o[i])=="object") {
            //going one step down in the object tree!!
            traverse(o[i],func);
        }
    }
}

//that's all... no magic, no bloated framework
traverse(o,process);

https://stackoverflow.com/questions/722668/

相关文章:

javascript - 如何测试字符串是否为 JSON?

json - 如何在 Github Wiki 中设置 JSON block 的样式?

javascript - JSON.stringify 以 pretty-print 方式输出到 d

javascript - 如何从 JavaScript 中的 URL 获取 JSON?

android - 在 Android 中发送和解析 JSON 对象

json - 将 CSV/XLS 转换为 JSON?

javascript - 使用 Javascript 将 XML 转换为 JSON(并返回)

json - 在 ASP.NET 中使用 WebAPI 或 MVC 返回 JSON

c# - 如何从 URL 获取 JSON 字符串?

json - postman :发送嵌套的 JSON 对象