I have a multi level JSON like in the example below. I want to write a simple code to loop through it and fetch all the keys there are in it for validation purposes.
I tried Object.keys()
but that gives the keys only for the first level of the object. How do I loop it to get the whole result?
{
"id": "0001",
"ppu": 0.55,
"batters": {
"batter": [{
"id": "1001",
"type": "Regular"
},
{
"id": "1004",
"type": "Devil's Food"
}
]
},
"topping": {
"id": "5001",
"type": "None",
"moreData": {
"id": "5003",
"type1": "Chocolate",
"type2": {
"id": "5004",
"type": "Maple"
}
}
}
}
I normally get only the first keys, i.e. "id", "ppu","batters",topping" but I want all the keys including "batter", "type", "moreData", etc. NOTE: All my keys are unique unlike the example below.
EDIT - Code that I'm trying:
function keyCheck(obj) {
var a = Object.keys(obj);
var arr=[];
arr.push(a);
for (var i = 0; i < a.length; i++) {
var b = obj[a[i]];
if (typeof (b) == 'object') {
keyCheck(b);
}
}
return arr[0];
}
keyCheck(obj);