I am well aware of the existence of JSON.parse
and JSON.stringify
and prettier
the npm package. But for some reason I still have to do this by hand. Think of it as a coding interview question and please do not close this question simply because I could have used JSON.parse
and JSON.stringify
, as I said there is this constraint. And this question is NOT a duplicate of this pretty-print JSON using JavaScript
Here is a string "['foo', {bar:['baz',null,1.0,2]}]"
I wanted to implement a function to return a string denoting a json object with proper indentaion.
i.e. the output string should be
[
"foo",
{
"bar":
[
"baz",
null,
1.0,
2
]
}
]
Here is my attempt
function printJSON(str) {
let spaces = [];
let output = '';
str.split('').forEach(char => {
switch(char) {
case '{':
case '[':
spaces.push(' ');
output += char + '\n' + spaces.join('');
break;
case '}':
case ']':
spaces.pop();
output += '\n' + spaces.join('') + char;
break;
case ',':
output += char + '\n' + spaces.join('');
break;
default:
output += char;
break;
}
});
console.log(output);
return output
}
However the output format is slightly off as in
[
"foo",
{
bar:[ //
"baz",
null,
1.0,
2
]
}
]
How can I fix this format issue? also is there a more elegant way or alternative way to achieve this?