Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I output a javascript array where each array item is a new line using JSON.stringify

My goal is to take a javascript array object and output it to a string formatted in a way I can store it in a file. I want to use JSON.stringify because it's a lot more robust than my own function will be. If I have to I can just use a new function for it.

I have an array with multiple objects say [{"attr1":"val", "attr2":"val", "attr3":"val"}, {"attr1":"val", "attr2":"val", "attr3":"val"}, {"attr1":"val", "attr2":"val", "attr3":"val"}, ...] I need to store this in a text file in the format of

[{"attr1":"val", "attr2":"val", "attr3":"val"},
 {"attr1":"val", "attr2":"val", "attr3":"val"}, 
 {"attr1":"val", "attr2":"val", "attr3":"val"}, 
 ...]

I know I can pretty print with JSON.stringify, but it prints each attribute on a new line instead of printing each array item on a newline.

like image 390
darthNater Avatar asked May 23 '26 22:05

darthNater


1 Answers

Here's a one-liner:

const data = [{"attr1":"val", "attr2":"val", "attr3":"val"},{"attr1":"val", "attr2":"val", "attr3":"val"},{"attr1":"val", "attr2":"val", "attr3":"val"}]
 
const formatted = `[${data.map(JSON.stringify).join(',\n ')}]`
 
console.log(formatted)
like image 66
tex Avatar answered May 26 '26 12:05

tex



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!