简体   繁体   中英

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.

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)

You need to store every object of array in new line first, to do this you can do this simple loop:

 const arr = [{ "attr1": "val", "attr2": "val", "attr3": "val" }, { "attr1": "val", "attr2": "val", "attr3": "val" }, { "attr1": "val", "attr2": "val", "attr3": "val" }] let text = ''; for(let obj of arr){ text += JSON.stringify(obj) + '\\n' } console.log(text);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM