3

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.

3 Answers 3

4

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)

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

2 Comments

You might want to add an extra spacing right after \n to further improve the formatting of the JSON. ( Align new object item with the beginning square bracket )
Done! Thanks for the suggestion.
1

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

1 Comment

you may beed to add comma after every object or as you like the print to be
0

The accepted answer, produced typescript errors for me, and I also don't want "\n" after the last element. Here's what gave the output I wanted:

const arr = [{ "attr1": "val", "attr2": "val", "attr3": "val" },
{ "attr1": "val", "attr2": "val", "attr3": "val" },
{ "attr1": "val", "attr2": "val", "attr3": "val" }];
const [a0, ...aRest] = arr;
const formattedArr = `[${JSON.stringify(a0)},${aRest.map( (a) => "\n" + JSON.stringify(a) )}]`;
console.log(formattedArr);

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.