我想访问包含多个嵌套对象的json文件中的数据,并且想动态打印它们而无需考虑其中的数据是什么。我想在内部动态打印键值。
我的json
{
"name" : "abc",
"tags" : "def",
"updated-by" : "ijk",
"property" : {
"description" : "abcd",
"type" : "string"
},
"sources" : {
"input" : {
"type" : "lmn",
"properties" : {
"key" : "opq"
}
}
}
}
如果我的键包含对象,那么它应该进入该对象内部然后打印其值,但是如果它也是另一个对象,那么它也应进入该对象内部然后打印其键值。它应该动态循环。代码必须为4角或更高。如果有人可以提供帮助。
答案 0 :(得分:1)
您正在寻找的行为已被JSON.stringify(jsonObject)
方法覆盖。
您还可以控制间距和pretty print the JSON。
答案 1 :(得分:0)
您可以使用递归函数。
const myObj = {
"name" : "abc",
"tags" : "def",
"updated-by" : "ijk",
"property" : {
"description" : "abcd",
"type" : "string"
},
"sources" : {
"input" : {
"type" : "lmn",
"properties" : {
"key" : "opq"
}
}
}
}
function checkNested(obj) {
for (let prop in obj) {
if (obj.hasOwnProperty(prop)) {
if (typeof obj[prop] == "object"){
console.log(`Key: ${prop}`)
checkNested(obj[prop]);
} else {
console.log(`Key: ${prop} 'value: ${obj[prop]}`)
}
}
}
}
checkNested(myObj)