0

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.

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
  • What is the different? `\` is an escape char. – Alen.Toma Mar 21 '22 at 18:52
  • 1
    JSON is only ever a string. Other than not having a space between `"a":` and `1` (yeah... don't), you *could* parse to a JavaScript object, then stringify and give it a parameter to tell it to indent. – crashmstr Mar 21 '22 at 18:54
  • Does this answer your question? [Safely turning a JSON string into an object](https://stackoverflow.com/questions/45015/safely-turning-a-json-string-into-an-object) – Emile Bergeron Mar 21 '22 at 18:55
  • While re-reading the question, I figured that [this old question](https://stackoverflow.com/q/4810841/1218980) would fit more than the one I suggested above. – Emile Bergeron Mar 21 '22 at 18:58
  • And to render pre-formatted code, you might want to look at this one: https://stackoverflow.com/q/37213957/1218980 – Emile Bergeron Mar 21 '22 at 19:01

2 Answers2

1

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));
hurricane
  • 6,521
  • 2
  • 34
  • 44
0

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);
hadhulls
  • 1
  • 1