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.
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?
prettier) that do this very well alreadyt?.constructorhere?t.constructorallows us to check the type of anyt. however because we want to allowtto benullorundefined, we use nullish coalescing?.to prevent property lookup on a null. You can see this technique used in some of my other answers."['foo', {bar:['baz',null,1.1,2]}]", the output will be an unformatted string.