javascript - 如何使用节点 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' 的情况下它们具有相同类型的值,但它们的值数量不同。
有人可以帮我吗?:(
解决方案
您可以使用递归和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 - 如何在 Pixi.js 中制作手绘文本动画?
- laravel - 将文件从一台电脑传输到另一台电脑时,图像网址的 Laravel 问题
- unity3d - 摆脱“后处理包需要全屏使用”警告(Mac,内置管道)
- go - 使用 crypto/ssh 和 golang 运行 iperf3
- c# - 如何为 this/instance=null 动态调用非静态 System.Object::Equals(object) (例如通过反射)?
- java - 从扩展父类访问值时出现 Java NullPointerException
- c# - 备用键的逆属性
- google-apps-script - getRange 和 setRange 未正确粘贴
- apache - MAMP 虚拟主机总是指向 documentRoot
- amazon-web-services - AWS Kinesis Firehose 没有向 Elasticsearch 发送数据......IAM 权限?