Skip to content

Instantly share code, notes, and snippets.

@zz85
Last active June 10, 2023 19:16
Show Gist options
  • Save zz85/8362569f07c1e7eb64e3236ac931db82 to your computer and use it in GitHub Desktop.
Save zz85/8362569f07c1e7eb64e3236ac931db82 to your computer and use it in GitHub Desktop.
Pretty Print JSON in Ascii Tree
// TODO add colors
sample = { a: { b: { c: 1, moo: [3,2,1] } }, z: 'zzzz' }
const asciitree = require('ascii-tree');
function pretty_json(v) {
console.log(JSON.stringify( v, 0, 2 ))
}
function ascii_json(json) {
const list = ['#root'];
_traverse(list, json, 1);
const tree = asciitree.generate(list.join('\r\n'));
console.log(tree)
}
function _traverse(list, node, level) {
level++;
const prefix = Array(level + 1).join('#');
const type = typeof node;
if (node === undefined || node === null) {
// Array.isArray([])?
list.push(prefix + node);
}
else if (type === 'object') {
Object.keys(node).forEach(k => {
list.push(prefix + k);
_traverse(list, node[k], level);
});
}
else {
// string boolean
list.push(prefix + node);
}
}
pretty_json(sample)
ascii_json(sample)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment