Created
August 12, 2016 07:45
-
-
Save pisceanfoot/5b2f747d2c74c932956f69c8e48c0198 to your computer and use it in GitHub Desktop.
display JSON in a tree format
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function render(data, indent, fromArray) { | |
if(data == undefined){ | |
return ''; | |
} | |
var preAppend = ''; | |
if(indent){ | |
preAppend = new Array(indent * 4 + 1).join(' '); | |
}else{ | |
indent = 0; | |
} | |
var array = []; | |
if(Array.isArray(data)){ | |
array.push('') | |
data.forEach(function (item) { | |
var value = render(item, indent, true); | |
array.push(preAppend + value); | |
}); | |
}else if(typeof data == 'object'){ | |
if(!fromArray && indent) | |
array.push(''); | |
var first = true; | |
for(var key in data){ | |
var value = data[key]; | |
var result = render(value, indent + 1); | |
if(fromArray && first){ | |
array.push(key + ":" + result); | |
first = false; | |
}else{ | |
array.push(preAppend + key + ":" + result); | |
} | |
} | |
}else{ | |
return data; | |
} | |
return array.join('\n'); | |
} | |
var info = { | |
a: 1, | |
b: 2, | |
d: { | |
a: 1, | |
b: 2, | |
c: { | |
a: 1 | |
}, | |
e: [1,2,3] | |
}, | |
e: [ | |
1,2,3 | |
], | |
f: [ | |
{ | |
a: 1, | |
b: 2, | |
d: [12,3,4,], | |
e: { | |
a: 1, | |
b: 2 | |
}, | |
f: [ | |
{ | |
a: 1 | |
} | |
] | |
} | |
] | |
}; | |
var array = []; | |
var xxx = render(info); | |
console.log('\n\nend ====>>>>'); | |
console.log(xxx); | |
// console.log(array.join('\n'));; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.