Skip to content

Instantly share code, notes, and snippets.

@pisceanfoot
Created August 12, 2016 07:45
Show Gist options
  • Save pisceanfoot/5b2f747d2c74c932956f69c8e48c0198 to your computer and use it in GitHub Desktop.
Save pisceanfoot/5b2f747d2c74c932956f69c8e48c0198 to your computer and use it in GitHub Desktop.
display JSON in a tree format
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'));;
@pisceanfoot
Copy link
Author

pisceanfoot commented Aug 12, 2016

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment