1

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.

5
  • What is the different? `` is an escape char. Commented Mar 21, 2022 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. Commented Mar 21, 2022 at 18:54
  • Does this answer your question? Safely turning a JSON string into an object Commented Mar 21, 2022 at 18:55
  • While re-reading the question, I figured that this old question would fit more than the one I suggested above. Commented Mar 21, 2022 at 18:58
  • And to render pre-formatted code, you might want to look at this one: stackoverflow.com/q/37213957/1218980 Commented Mar 21, 2022 at 19:01

2 Answers 2

5

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));

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! The responses on stackoverflow.com/questions/30765163/… omit JSON.parse(), which is the key to correctly formatting.
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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.