My current task involves making external API calls that return JSON objects. Once all the calls are completed, I intend to write the collection of JSON objects to a file. However, I'm encountering an issue where the data is being written to the file in the incorrect format.
UPDATE: The findPrices() function is invoked within a loop.
priceSearch1Array = [];
function findPrices(res) {
(api.get({
origin: A,
destination: B,
}).then(function(response) {
priceSearchVar = JSON.stringify(response.result.data);
priceSearch1Array.push(priceSearchVar);
}).catch(function(error) {
console.log('error and continue' + error);
}))
}
Once all API calls are made, the array containing the data is saved to a file.
fs.writeFileSync('api/data/destinations3.json', priceSearch1Array);
The current output looks like this:
[{flight:"data", segments: { price:"23.22"}}],
[{flight:"data", segments: { price:"78.45"}}],
[{flight:"data", segments: { price:"48.45"}}]
However, I require the data to be written in the following format:
[
{flight:"data", segments: { price:"23.22"}},
{flight:"data", segments: { price:"78.45"}},
{flight:"data", segments: { price:"48.45"}}
]
I need the JSON objects to be presented as a list and then added to the file rather than having each object stored as an individual array. Is there a way to achieve this?