I've written a function to prettify a json object, as if it were using JSON.stringify.
I'm only focused on strings and other objects, nothing else.
Is there a better way of doing this? perhaps using a data structure?
const exampleJson = {"name":"Jon","facts":{"car":"Ford","address":{"city":"New York"},"watch":"Casio","other": {}}};
function prettyPrint(data) {
let tabbify = n => Array(n).fill(' ').join('');
let traverse = (data, tab = 1) => {
let output = "",
open = `{\n`,
close = `\n${tabbify(tab - 1)}}`;
output += open;
Object.entries(data).forEach(([key, val], i, {length}) => {
if (typeof val === 'string') {
output += `${tabbify(tab)} "${key}": "${val}"`;
} else if (typeof val === 'object') {
if (Object.keys(val).length > 0) {
output += `,\n${tabbify(tab)} "${key}": ${traverse(val, tab+2)}${i === length - 1 ? '' : ',\n'}`;
} else {
output += `,\n${tabbify(tab)} "${key}": {}`;
}
}
})
output += close;
return output;
}
return traverse(data);
}
Output
{
"name": "Jon",
"facts": {
"car": "Ford",
"address": {
"city": "New York"
},
"watch": "Casio",
"other": {}
}
}