M
M
Max Mykhailenko2019-12-02 18:30:21
JavaScript
Max Mykhailenko, 2019-12-02 18:30:21

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

This is what is saved in the json file
{"NumberStop":26,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1},{"NumberStop":90,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1},{"NumberStop":27,"NumberBus":9,"AvgCountPassengers":5,"DayOfWeek":1}

And I need to parse the file and so that each such line would simply be entered into an array element.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
V
Vladimir Korotenko, 2019-12-02
@firedragon

You are overwriting the file use append
fs.appendFileSync("data.json", kol);

D
DENIS Kokorev, 2019-12-02
@shmaroder

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 question

Ask a Question

731 491 924 answers to any question