While I am familiar with JSON.parse
, JSON.stringify
, and the npm package prettier
, for some reason I still find myself manually handling this task. Let's approach it as a coding interview question without dismissing it due to not using JSON.parse
and JSON.stringify
as specified.
Given the string:
"['foo', {bar:['baz',null,1.0,2]}]"
I aim to create a function that returns a properly indented JSON object string.
Desired output of the string:
[
"foo",
{
"bar":
[
"baz",
null,
1.0,
2
]
}
]
This is my current 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, there is a formatting issue with the output, such as:
[
"foo",
{
bar:[ // 🚨
"baz",
null,
1.0,
2
]
}
]
How can I rectify this format issue? Is there a more elegant or alternative method to achieve this?