简体   繁体   中英

Save arrays to JSON file and then use Array.push() to save data in it

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.

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

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.parse ing it into a javascript object(or array) modifying it and re-writting the file with the new object(or array)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM