Save an object array into one text record per array element

56 Views Asked by At

I have an application which, from time to time, saves object arrays into text files. All the elements of the object array display identical structure.

As an example, consider the following object array:

[{"A":1,"B":2},{"A":11,"B":22},{"A":111,"B":222}]

The need is to save this into a file such that it would look like this:

[{"A":1,"B":2} , 
{"A":11,"B":22} , 
{"A":111,"B":222}]

meaning, one record within the text file for each object in the array.

The reason for that is that those arrays may include hundreds and up to several thousands of elements and I wish to keep these files READABLE for humans.

Is there any trick that can be invoked when using the standard JSON.stringify method? If not, any other suggestion will be appreciated.

2

There are 2 best solutions below

1
Alexander Nenashev On BEST ANSWER

Just stringify individual items.

const data = [{"A":1,"B":2} , 
{"A":11,"B":22} , 
{"A":111,"B":222}];

let str = '[';
data.forEach((item, i) => str += (i ? ' ,\n' : '') + JSON.stringify(item));
str+=']';

console.log(str);

You could use map().join() but it's a bit slower.

const data = [{"A":1,"B":2} , 
{"A":11,"B":22} , 
{"A":111,"B":222}];

const str = `[${ data.map(JSON.stringify).join(' ,\n') }]`;

console.log(str);

` Chrome/122
--------------------------------------------------------------------------------
>                    n=3      |      n=30       |     n=300      |    n=3000    
string concap   1.00x x1m 239 | 1.00x x100k 209 | 1.00x x10k 210 | 1.00x x1k 209
map().join()    1.05x x1m 252 | 1.10x x100k 229 | 1.10x x10k 231 | 1.15x x1k 240
--------------------------------------------------------------------------------
https://github.com/silentmantra/benchmark `

const $chunk = [{"A":1,"B":2} , 
{"A":11,"B":22} , 
{"A":111,"B":222}];

const $input = [];
const data = $input;

// @benchmark string concap
let str = '[';
data.forEach((item, i) => str += (i ? ' ,\n' : '') + JSON.stringify(item));
str+=']';

// @benchmark map().join()
`[${ data.map(JSON.stringify).join(' ,\n') }]`;



/*@end*/eval(atob('e2xldCBlPWRvY3VtZW50LmJvZHkucXVlcnlTZWxlY3Rvcigic2NyaXB0Iik7aWYoIWUubWF0Y2hlcygiW2JlbmNobWFya10iKSl7bGV0IHQ9ZG9jdW1lbnQuY3JlYXRlRWxlbWVudCgic2NyaXB0Iik7dC5zcmM9Imh0dHBzOi8vY2RuLmpzZGVsaXZyLm5ldC9naC9zaWxlbnRtYW50cmEvYmVuY2htYXJrL2xvYWRlci5qcyIsdC5kZWZlcj0hMCxkb2N1bWVudC5oZWFkLmFwcGVuZENoaWxkKHQpfX0='));

1
r0den On

While this will not give the exact result you're looking for (breaking the line for individual array elements, rather than for the whole JSON), consider taking a look into the space parameter of the JSON.stringify method, which will add indentation and spacing and perhaps, will store the JSON in a more human-readable form.