I'm trying to print a json string in a json format.
So, the input would be something like: "{\"a": 1, \"b\":\"2\"}"
I need the output to look like this:
{
"a":1,
"b":"2"
}
I have tried using JSON.stringify but it just prints out the same string. Any help is appreciated.
CodePudding user response:
Parse your string to js object, than parse it to string to with new lines.
console.log(JSON.stringify(JSON.parse('{\"a": 1, \"b\":\"2\"}'), null, 2));
CodePudding user response:
Before just running below code you should make a small change.
"{\"a": 1, \"b\":\"2\"}" ->
"{\"a\": 1, \"b\":\"2\"}"
const stringifiedJson = "{\"a\": 1, \"b\":\"2\"}";
const result = JSON.parse(json);
console.log(result);