Answer the question
In order to leave comments, you need to log in
How to put objects that are taken from the database into a json file?
There is a code that takes data from the database, converts it to json format and puts it in an array, everything would be fine, but when I open the file in which the data was written, I find that the objects simply lie through "," from each other, although I write the whole array to the file. Here is the code for the entry:
function queryDatabase() {
var i = 0;
console.log(`Running query to PostgreSQL server: ${config.host}`);
const query = 'SELECT * FROM \"Stop\"';
client.query(query)
.then(res => {
const rows = res.rows;
rows.map(row => {//The code is responsible for taking data and putting it in a file
console.log(`Read: ${JSON.stringify(row)}`);
kol[i] = `${JSON.stringify(row)}`;
++i;
});
fs.writeFileSync("data.json", kol);
console.log(kol);
process.exit();
})
.catch(err => {
console.log(err);
});
}
{"NumberStop":26,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1},{"NumberStop":90,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1},{"NumberStop":27,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1}
Answer the question
In order to leave comments, you need to log in
You are overwriting the file use append
fs.appendFileSync("data.json", kol);
Parentheses [] forgot at the beginning and end. Then there will be an array.
[{"NumberStop":26,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1},{"NumberStop":90,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1},{"NumberStop":27,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1}]
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question