Currently, I am utilizing Javascript along with NodeJS to dynamically generate an array of JSON objects. My goal is to store this array of JSON objects in a .json file for future reference. However, when I attempt to save the file, I encounter an issue where the contents are separated by commas only, without the enclosing square brackets.
The method I am using for this process is fs.writeFile. The dynamically created array contains JSON objects which are separated by commas. Below, you can find the function I have implemented:
fs.writeFile('json_files/output_'+id+'.json', ret_vals, function (err) {
if (err)
return console.log(err);
console.log('Success!');
});
The resulting file output looks like this:
{"x":"y"}, {"x":"z"}, {"x":"t"}
However, my desired format for the .json file should be as follows:
[{"x":"y"}, {"x":"z"}, {"x":"t"}]In essence, I want the array brackets to be included. To provide more context, I create an array named ret_vals using let ret_vals = [], and then utilize .push() to add these JSONs to it.
If I attempt to use stringify, although I do get the brackets, the array content itself is enclosed within quotation marks. This renders it challenging to perform any comparisons on the JSON data since it would recognize the entire sentence as different. How should I proceed to achieve the desired outcome?