28

I'm writing a simple JS app that takes in a JSON file, displays the information to the user and allows them to modify it, and then allows them to re-export the JSON. However, the JSON that is being brought in is multi-line; each key/value is on its own line. When I use .stringify to output the JSON, it all appears on one line. Is there any way for the stringify method to separate the lines?

JSON Structure:

{"Title":
 {"lvlOne":[
  {"key":"val"},
  {"key":"val"},
  {"key":"val"}
 ],
 "lvl2":[
  {"key":"val"},
  {"key":"val"},
  {"key":"val"}
 ]}
}

But when I output, it all shows:

{"Title":{"lvlOne":[{"key":"val"},{"key":"val"},{"key":"val"}],"lvl2":[{"key":"val"{"key":"val"},{"key":"val"}]}}
3
  • 1
    Please research JSON.stringify: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… - a third parameter can be used to specify the spacing for pretty printing Commented Jul 1, 2014 at 17:19
  • Where do you print this output ? Commented Jul 1, 2014 at 17:32
  • I populate a <textarea> with the JSON for the user to copy and deploy. Commented Jul 1, 2014 at 17:36

4 Answers 4

53

You can use the space parameter of the stringify method. From the official page, here is the relevant excerpt:

JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'
Sign up to request clarification or add additional context in comments.

2 Comments

why " " helps to add a new line instead of just a space ?
for me (vue3) numbers work fine, too. but the null is relevant, as JSON.stringify(obj, space=2) isn't working as expected :/
11

you can also use.

var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, '\t');
console.log(json);

Comments

8

Or even better, the count of spaces in the indentation:

var json = JSON.stringify({ uno: 1, dos : {"s":"dd","t":"tt"} }, null, 2);

1 Comment

this prints on multiple lines - not good
-3

None of the above worked for me the only thing that worked for me was

await fs.promises.writeFile('testdataattr.json',JSON.stringify(datatofile, null,'\r\n'),'utf8') ;

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.