Joey N
Joey N

Reputation: 368

JSON Stringify Ouput to Multiple Lines

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"}]}}

Upvotes: 27

Views: 33606

Answers (4)

GMC
GMC

Reputation: 1

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

Upvotes: -1

Gabriel Anderson
Gabriel Anderson

Reputation: 1391

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

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

Upvotes: 8

Mike Pelley
Mike Pelley

Reputation: 3116

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}'

Upvotes: 52

Maneesh Singh
Maneesh Singh

Reputation: 575

you can also use.

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

Upvotes: 11

Related Questions