Store the arrays in a JSON file before utilizing Array.push() to append data into it

I'm currently developing a calendar software and I want to store events in a JSON file. My strategy involves nesting arrays within arrays in the JSON format, allowing for easy iteration and loading during program initialization.

My main question is: how can I add an array into another array in JSON? Any tips on this issue? For instance, if I have a variable var event containing an array such as

{"id": elementTitle, "year": year, "month": month, "day": day};
which will be stringified using JSON.stringify(event), how do I append it to an existing array in a JSON file like: events = { }.

Just to add, this application is built using the electron API and powered by node.js.

Answer №1

You may consider implementing this approach.

Specify events using [] to indicate that it is an array.

//file.json

{
  "events":[]
}

Utilize the node filesystem or "fs" module to interact with your file. The code snippet below demonstrates asynchronous reading and writing, allowing the application to continue running without pauses - although synchronous options are also available.

//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 {
                  //All operations completed successfully!
            }});
   }

});

Further examples

Answer №2

In my code, I have a variable called event which is set to an object {"id": elementTitle, "year": year, "month": month, "day": day}

Just to clarify, this data structure is actually an object, not an array.

To update a JSON file that has been saved to disk, you would need to read the file from disk, parse it using JSON.parse to convert it into a JavaScript object (or array), make your modifications, and then overwrite the file with the updated object (or array).

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using jQuery to find duplicated records within two JSON object arrays

Here is the structure of my first Json Array: [ {"Invent":"4","Beze":"256","mail":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="96f7f4f5d6f7f4f5b8f5f9fb">[email protected]</a>"}, {"Invent":"4","Beze":"2 ...

Is it feasible for a JavaScript function to receive the innerHTML of the element from which it is invoked as an argument?

Is there a way to bind a function that takes a String as a parameter to a button so that it is called onclick and takes the innerHTML of the element as a parameter, without assigning the button an id or using queryselector? <button onclick="myFunct ...

Turn off info windows for businesses and other points of interest, except for those within your own polygons on Google Maps

Is there a way to make only the infowindows attached to my polygons clickable on Google Maps? I don't want Points of Interests like Restaurants to have clickable infowindows. I tried changing the map style to hide business labels, but infowindows stil ...

How can I create a custom Sweet Alert button in JavaScript that redirects to a specific webpage when clicked?

Here's what I have in my code: swal({ title: 'Successfully Registered!', text: "Would you like to proceed to the Log In page?", type: 'success', showCancelButton: true, confirmButtonColor: '#308 ...

What could be causing the removal of style classes from my element after it is appended?

Could you please explain how it functions? I am attempting to append a div with content using innerHTML and it is working, but without any of the styling classes being applied. const element = document.createElement("div"); element.classList.add("col ...

how to toggle visibility of bootstrap accordion panel using jQuery

I have a bootstrap accordion that I want to customize. Specifically, I only want to enable a panel under specific conditions. The idea is for the second panel to be collapsible only when the first panel is valid. <div class="panel-group" id="accordion" ...

Animated scrolling in Angular

I am working on a webpage using Angular, where each module is a component with an animation. However, I am facing an issue where the animation only runs when the page loads, but I want it to happen while the component is visible on the screen. One approa ...

React Hooks: Unable to re-enable input after it has been disabled

Attempting to manage the status of my points input whether it's enabled or disabled, I encountered an issue. Upon checking the checkbox, it correctly gets disabled. However, upon unchecking it, the input remains disabled. Initially, I attempted settin ...

Tips for creating a responsive div that contains both an image and description, including automatically resizing the image to fit the

#content { background-color: #ACAE4C; float: right; display: inline-block; padding: 0; } <div id="content"> <div class="pic"></div> <div class="desc"></div> </div> I need assistan ...

Creating a Cross Fade Animation effect with the combination of CSS and JavaScript

I've been attempting to create a similar animation using html and css. Below gif shows the desired outcome I am aiming for: https://i.sstatic.net/YsNGy.gif Although I have tried the following code, I have not been able to achieve the desired result ...

Tips for extracting text from a selenium webelement icon that displays hovertext

Let's use Amazon as an example. Suppose we want to extract the star rating for a product. When hovering over the stars, we see a text element that says "4.0 out of 5 stars" and upon inspecting the code, we find: <span class="a-icon-alt">4.0 ou ...

What could be improved in this AngularJS code snippet?

Currently, I am immersed in an AngularJS book and have extracted the following code snippet directly from its pages: <!DOCTYPE html> <html ng-app='myApp'> <head> <title>Your Shopping Cart</title> </head> & ...

Ways to resolve the issue of truncated lines while displaying HTML content in WebView on Android devices

When displaying content in a WebView, I am encountering an issue where the top and bottom lines are being cut off. What steps can I take to resolve this problem? My current approach involves using HTML to present data within the WebView. ...

Tips for utilizing variables as the initial value of a JSON Object

Here is a JSON configuration example: { "Users" : { "182723618273612" : 15, "AddedUser" : 1 } } I have generated this field using a JavaScript function, but now I want to change the name of "AddedUser" ...

Tips for disregarding global CSS in Nuxt.js?

I've been utilizing a boilerplate that integrates with the CoreUI template from GitHub, and it's been working well. However, I am now looking to customize my index page with a unique style, and I'm encountering issues where the global CSS fr ...

Adjusting the width of an image in Safari

I just launched my website, but I encountered an issue with the image size in Safari. In my CSS, I set the width like this: img { width: 450%; } Here is the site: I can't figure out why the images display correctly in Chrome and Mozilla, but ...

Guide on incorporating a dropdown menu within a Jssor slider

I am facing an issue with trying to include a dropdown menu inside the Jssor slider. The menu does not drop down when placed inside it. Here is the code snippet: <head> <script src="jquery.js"></script> <script src="jssor.slider.min. ...

Choose from a variety of options for color schemes and hover effects

Looking to create a selector where users can pick a color. I tried changing the background color for each option, but when hovering over them, the background turns blue - which is not what I want. Check out the pictures for clarification: https://i.sstatic ...

What is the best way to arrange the elements vertically within a flex container?

In my current code snippet, I have the following setup: <section class="body1"> <h1 class="text1">Tours around the world</h1> <h3 class="text1">Great experiences</h3> <form action="/respuestaUsuario/"> ...

Responsive design parameters

After creating a media query specifically for phones, I realized that I needed one for desktop as well. @media screen and (max-device-width: 480px), screen and (max-width: 480px) { ...css here... body {width:50%;} However, when I attempted to add a sim ...