我一直在使用复杂的嵌套 JSON 文件,如下所示:
更新::嵌套 JSON 文件片段(示例)
{
"sample": {
"someitem": {
"thesearecool": [
{
"neat": "wow"
},
{
"neat": "tubular"
}
]
},
"coolcolors": [
{
"color":"red",
"hex": "ff0000"
},
{
"color":"blue",
"hex":"0000ff"
}
]
}
}
我想遍历这个 JSON 文件中的每个值。 我尝试过许多 npm nodejs 包将嵌套 JSON 转换为简单、可读的 JSON 格式。(NPM Packages-> flattenr、flat 等)。
请有人帮我解决这个问题。请给出一些更好的解决方案并举例说明。
最佳答案
是的,这是一个很好的递归问题。 因此,总体思路是一个带有 for 循环的函数。
可能发生两种情况:要么它是一个值,然后打印它。或者它是一个对象,然后您将该对象放入相同的函数中。
<div id="log"></div>
<script>
var data = {
"sample": {
"someitem": {
"thesearecool": [
{
"neat": "wow"
},
{
"neat": "tubular"
}
]
},
"coolcolors": [
{
"color":"red",
"hex": "ff0000"
},
{
"color":"blue",
"hex":"0000ff"
}
]
}
};
function readAllJson(data, level) {
var resultString = '';
for(var i in data) {
var type = typeof data[i];
switch(type) {
case 'object':
resultString += indent(level) + i +':<br/>'+ readAllJson(data[i], level + 1); // recursion
break;
default:
resultString += indent(level) + i +': '+ data[i] + '<br/>';
break;
}
}
return resultString;
}
function indent(level) {
var result = '';
for(var i=0; i<level; i++) {
result += ' '; // HTML space character
}
return result;
}
window.onload = function() {
var log = document.getElementById('log');
var result = readAllJson(data, 0);
log.innerHTML = result;
}
</script>
关于javascript - 使用 Node js 以简单的键->值对格式读取 javascript 中的嵌套 json 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40787215/