0

I am creating a calendar program, and my aim is to save events and so on in a JSON file. What I think is the best way to do so is by storing arrays inside arrays in the JSON file (this way I can iterate through each array and load them when the program starts).

First and foremost: how do I push an array into an array in JSON? Any suggestions? Say for example I have variable var event that is equal to an array {"id": elementTitle, "year": year, "month": month, "day": day}; that is going to be JSON.stringify(event)'ed. So how do I save this to an array already created in a JSON file?: events = { }.

By the way, this program is created with the electron api, also using node.js.

2 Answers2

1

You could do something like this.

Declare events using [] signifying that it is an array.

//file.json

{
  "events":[]
}

Using the node filesystem or "fs" module you can read and write to your file. The example below uses asynchronous reading and writing so the application will not stop and wait - but you can do this synchronously as well.

//app.js

let fs = require('fs');

fs.readFile('/path/to/local/file.json', 'utf8', function (err, data) {
   if (err) {
       console.log(err)
   } else {
       const file = JSON.parse(data);
       file.events.push({"id": title1, "year": 2018, "month": 1, "day": 3});
       file.events.push({"id": title2, "year": 2018, "month": 2, "day": 4});

       const json = JSON.stringify(file);

       fs.writeFile('/path/to/local/file.json', json, 'utf8', function(err){
            if(err){ 
                  console.log(err); 
            } else {
                  //Everything went OK!
            }});
   }

});

More examples

Natalie
  • 331
  • 4
  • 14
  • Hey, thanks for answering! I put your answer as the correct one, because it shows very easily how it is done. But anyhow, how do I access the id property in the first object in the array? Is it `file.events[0].id`? EDIT: Nevermind, I tested it out, and it worked :) – Frikk Ormestad Larsen Mar 06 '18 at 20:27
0

I have variable var event that is equal to an array {"id": elementTitle, "year": year, "month": month, "day": day}

this isn't an array, it's an object

anyway, the way you'd modify a json that you saved to disk is by reading it from disk, JSON.parseing it into a javascript object(or array) modifying it and re-writting the file with the new object(or array)

sudavid4
  • 1,081
  • 6
  • 14