Reputation: 19
Suppose I have the following JSON object:
{"root":{"Child":0, "Child1":0, "Child2":[0, 0, 0, 0]}}
This JSON object may be complex.
I'm interested in printing each input path from my complex JSON object in JQUERY. My output should look like:
{"root":{"Child":0}}
{"root":{"Child1":0}}
{"root":{"Child2[0]":0}}
{"root":{"Child2[1]":0}}
{"root":{"Child2[2]":0}}
{"root":{"Child2[3]":0}}
How would you print a complex JSON object in this way without specifying the name of JSON variables in Jquery?
Upvotes: 1
Views: 335
Reputation: 8181
Here is my dirty jQuery (since your question is tagged) version:
Demo1@Fiddle
Demo2@Fiddle
var json = $.parseJSON('{"root":{"Child":0, "Child1":0, "Child2":[0, 0, 0, 0]}}'), arr = [], arrVal;
$.each(json, function(key, val) {
if (typeof val === "object") {
$.each(val, function(key1, val1) {
if (typeof val1 === "object") {
$.each(val1, function(key2, val2) {
arrVal = ['{"', key , '":{"', key1, '[', key2, ']":', val2, '}}'].join("");
arr.push(arrVal);
});
} else {
arrVal = ['{"', key, '":{"', key1, '":', val1, '}}'].join("");
arr.push(arrVal);
}
});
}
});
Upvotes: 0
Reputation: 492
Tried a recursive approach to print all properties.
var json={"root":{"Child":0, "Child1":0, "Child2":[0, 0, 0, 0]}}
function prettyPrint(json,path,depth)
{
var keys=Object.keys(json);
if(keys.length==0)
{
var outp=path+":"+json;
for(var i=0;i<depth;i++)
{
outp+="}";
}
console.log(outp);
}
else
{
depth++;
for(var i=0;i<keys.length;i++)
{
prettyPrint(json[keys[i]],path+":{"+keys[i],depth);
}
}
}
prettyPrint(json,"",0);
Output is
{root:{Child:0}}
{root:{Child1:0}}
{root:{Child2:{0:0}}}
{root:{Child2:{1:0}}}
{root:{Child2:{2:0}}}
{root:{Child2:{3:0}}}
Alter this fiddle to suit to your needs
http://jsfiddle.net/cwmgwok4/1/
Upvotes: 1
Reputation: 3892
Hope you are looking for it, but this looks weird though :P
var obj = {"root":{"Child":0, "Child1":0, "Child2":[0, 0, 0, 0]}};
for (var item in obj){
if(typeof obj[item] == 'object'){
for (key in obj[item]) {
if (obj[item].hasOwnProperty(key)) {
if(typeof obj[item][key] == 'object'){
for(var keyValue in obj[item][key]){
//console.log(obj[item][key][keyValue])
console.log('{'+item+':'+'{'+key+':'+obj[item][key][keyValue]+'}}') ;
}
}
else{
console.log('{'+item+':'+'{'+key+':'+obj[item][key]+'}}') ;
}
}
}
}
}
Upvotes: 0