我正在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”是同一级别的数据,但同时它们具有不同的(数组和对象)值类型,并且在“讲师”的价值观类型相同,但价值观的数量不同。
有人可以帮我吗?:(
答案 0 :(得分:1)
您可以使用递归和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)
答案 1 :(得分:0)
您可以尝试使用像这样的递归函数迭代这些值
var Obj {
//Contents
}
function printRec(obj){
if(Object.keys(obj).length>0||Array.isArray(obj)){
for(elem in obj){
printRec(obj);
}
}else{
//Process Value
console.log(obj)
}
}