首页 > 解决方案 > 如何使用节点 js 遍历不规则的嵌套 json

问题描述

我正在 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”是相同级别的数据,但同时它们具有不同的(数组和对象)类型的值,并且在 'instructors' 的情况下它们具有相同类型的值,但它们的值数量不同。

有人可以帮我吗?:(

标签: javascriptnode.jsjsonnested

解决方案


您可以使用递归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)


推荐阅读