我在Nodejs上制作了一个小应用程序,并且正在尝试循环一个不规则的JSON以打印其数据。
我的JSON具有以下结构:
{
"courses": [
{
"java": [
{ "attendees": 43 },
{ "subject": "Crash course" }
]
},
{
"python":
{
"occurrences": [
{ "attendees": 24 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
,
{ "attendees": 30 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
]
}
}
],
"instructors":[
{
"John Doe":[
{ "hours": 20 },
{ "experience": 50 },
{ "completed": true }
]
},
{
"Anne Baes": [
{ "hours": 45 },
{ "experience": 40 },
{ "completed": false},
{ "prevExperience": true}
]
}
]
}
我想要做的是打印JSON中包含的所有数据(我想要类似的东西):
courses
Java
attendees = 43
...
Anne Baes
hours = 45
experience = 40
completed = false
prevExperience = true
我尝试过:
for(element in data){
console.log(`element = ${{element}}`);
}
它只打印:
element = [object Object]
element = [object Object]
(这很有意义,因为json由两个元素组成)
我试过嵌套行:
for(element in data){
这里的问题是有一个不规则的结构,我的意思是,“ java”和“ python”是相同级别的数据,但同时它们具有不同的(数组和对象)值类型,在“讲师”的情况下它们具有相同的值类型,但它们的值数量不同。
有人可以帮我吗?
最佳答案
您可以使用递归和for..in
循环来实现
const obj = {
"courses": [
{
"java": [
{ "attendees": 43 },
{ "subject": "Crash course" }
]
},
{
"python":
{
"occurrences": [
{ "attendees": 24 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
,
{ "attendees": 30 },
{ "subject": "another crash course" },
{ "notes": "completed with issues" }
]
}
}
],
"instructors":[
{
"John Doe":[
{ "hours": 20 },
{ "experience": 50 },
{ "completed": true }
]
},
{
"Anne Baes": [
{ "hours": 45 },
{ "experience": 40 },
{ "completed": false},
{ "prevExperience": true}
]
}
]
};
function print(obj,isArr = false){
for(let key in obj){
if(typeof obj[key] === 'object'){
if(isArr === false) console.log(key)
print(obj[key],Array.isArray(obj[key]));
}
else console.log(`${key} = ${obj[key]}`)
}
}
print(obj)
关于javascript - 如何使用 Node js遍历不规则的嵌套json,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54735876/