[英]How to iterate over an irregular nested json with node js
我在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)
您可以嘗試使用遞歸函數迭代這些值
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)
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.