I'm writing a simple PrettyPrint function that only traverses shallowly through strings and objects.
I think it's pretty close
it's just
{
"name": "Jon",
"facts": {
"car": "Ford",
"address": {
"city": "New York"
},
"watch": "Casio",
"other": {}
},
}
the }, and the space after that before the closing bracket, how do I fix that so it outputs as if JSON.Stringify would?
{
"name": "Jon",
"facts": {
"car": "Ford",
"address": {
"city": "New York"
},
"watch": "Casio",
"other": {}
}
}
const exampleJson = {"name":"Jon","facts":{"car":"Ford","address":{"city":"New York"},"watch":"Casio","other": {}}};
const prettify = obj => {
tabs = n => Array(n).fill(' ').join('');
let traverse = (obj, tab = 1) => {
let markup = '{\n';
Object.entries(obj).forEach(kv => {
const [key, val] = kv;
if (typeof val === 'string') {
const { length } = Object.keys(val);
markup += `${tabs(tab)} "${key}": "${val}"`;
} else if (typeof val === 'object') {
const { length } = Object.keys(val);
if (length > 0) {
markup += `,\n${tabs(tab)} "${key}": ${traverse(val, tab+2)},\n`;
} else {
markup += `,\n${tabs(tab)} "${key}": {}`;
}
}
})
markup += `\n${tabs(tab - 1)}}`;
return markup;
}
let results = traverse(obj);
console.log(results);
}
prettify(exampleJson);