Adding to object in an external JSON file using javascript

I am working with an external file called file.json which contains the following values:

{
    "number": "value"
}

My goal is to run a function that will append new data to the existing file instead of overwriting it. For instance, after running the function, I would like the file to look like this:

{
    "number": "value"
},
{
    "number2": "newValue"
}

Currently, my attempts to achieve this using .push() have resulted in 'undefined'. Can anyone suggest how I can modify my code to successfully append data to the file?

Here is the code snippet I am currently using:

var urlList = require('./urlList.json');

app.get('/hello', function(req, res){

  var cat = 5;
  catNumber = "number" + cat;
  url = urlList[catNumber];

  request(url, function(error, response, html){
     if(!error){
     var $ = cheerio.load(html);

     var number;
     var json = { };

     $('.content').filter(function(){
        var data = $(this);
        title = data.children().first().text().trim();

        json.number = url;

  })
}

fs.writeFile('file.json', JSON.stringify(json, null, 4), function(err){
  console.log('File successfully written!');
})

Answer №1

If you have your JSON data stored in a file as an array structure like the following:

[
    {
        "item": "value"
    }
]

You can easily read the JSON data as an array and make any necessary modifications to it using the following code snippet:

const fs = require('fs');
fs.readFile('./data.json', (err, data) => {
  const jsonDataArray = JSON.parse(data);

  jsonDataArray.push({
    item2: "newValue"
  });

  fs.writeFile('data.json', JSON.stringify(jsonDataArray));
});

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

Efficiently managing multiple database updates with PHP and JQuery

Having trouble processing multiple mySQL updates simultaneously? I have 4 select/option boxes fetching data from a db table and I want to update the database onChange using JQuery. It's working with one select module, but adding more causes issues. Th ...

Tips on sending JSON string from Controller action to View and utilizing it as a parameter for a JQuery function

$(document).ready(function () { function initializeMap(data) { var map; alert(data); map = new L.Map('map', { zoom: 8, layers: [OSM] }); var array = $.parseJSON(data); alert( ...

Exploring the dynamic world through HTML5 canvas and animated objects

Today I am exploring HTML 5 canvas and experimenting with moving 3 circles on the canvas. Based on my research, it looks like I need to continuously redraw the circles (perhaps every 60 milliseconds) and clear out the old circle before rendering the new on ...

Using different CSS classes interchangeably in AngularJS

Imagine you have a list with an unknown number of items, ranging from one to potentially dozens. You want to display five CSS classes in a regular alternating pattern. What would be the most effective approach to achieve this? Here is some sample HTML cod ...

Assistance with selecting elements using jQuery

I'm facing a challenge with a code that I cannot change. My goal is to introduce a selector that can choose (upon clicking) all elements below it until the next occurrence of the main element. The catch is that they are not nested, just stacked on top ...

Tips for fixing a type error in javascript/cypress

While learning cypress and javascript, I encountered this type error: TypeError: _testElements.default.selectionRow is not a function I have thoroughly reviewed the documentation for cypress but cannot seem to find any errors in my code. I'm hoping ...

Combining Jquery with Append to Dynamically Update PHP Variables

Code Snippet (index.html) <script> $(document).ready(function() { var interval = setInterval(function() { $.get("load_txt.php", { 'var1': 4, 'var2' : 52}, function(data){ $('#msg' ...

CompletePage script, individual automatic scrolling

Having trouble with my fullPage.js implementation. I have a total of 5 sections and I'm trying to set different scrolling behaviors for each section. Specifically, I want Sections 1 through 3 to auto-scroll and Section 4.1 to 4.2 to use normal scroll. ...

Ways to stop the location object from resetting in ReactJS when reloading the page

Currently, I am using Link to redirect and call another component. The code looks something like this: <Link to={{ pathname: "/app/" + app.appId, appDetail: { app: app } }}>> When I call the path /app/:appId, it triggers the AppDetails ...

What is the process for generating a null result cursor upon publication?

Is it possible to return an empty cursor in Meteor? Meteor.publish('example', function(id) { check(id, Match.Maybe(String)) if (!this.userId) return [] }) Although I want the publication to return an empty result when the user is not lo ...

Flask Server produces a response with a considerable delay when accessed through AJAX

I am currently running 2 servers on localhost, each with different ports. One of them is a basic flask server in Python and its code is provided below: from flask import Flask,jsonify from flask_cors import CORS app = Flask(__name__) CORS(app) @app.rout ...

Integrating Vue.js code into Laravel's Blade templates for enhanced functionality

I'm having trouble accessing data from a Vue component function in a Laravel blade template that includes the component. When I use this code, the page just loads as a blank page. However, if I remove the @ symbol from the blade span, the autocomplete ...

Pattern to find a particular, multi-line item within JSON array

Dealing with JSON lists can sometimes be tricky. Here is an example of what a JSON list might look like: [ { "accessType": "*", "principalType": "ROLE", "principalId": "$unauthenticated", "permission": "DENY" }, { ...

passport not initializing session with requests

I am currently utilizing passportJS for managing login and persistent sessions on the server backend. While everything functions properly when sending requests from the server frontend (a webpage that I didn't create and lack sufficient knowledge to ...

The list indexes are required to be either integers or slices, not strings. Additionally, the JSON object should be a string, bytes, or bytearray, not a list

Looking at the code snippet below, I'm in the process of developing a function that aims to retrieve the order ID of a trade from Binance. Despite receiving all trade data in JSON format, I encountered two errors when attempting to access the data usi ...

Encountering issues with implementing router.push in Reactjs

Currently, I am working on ReactJS and utilizing Next.js. My current task involves refreshing the page (using routes), but I encountered an error message stating: Error: No router instance found. You should only use "next/router" inside the client-side of ...

Puppeteer: Easier method for managing new pages opened by clicking a[target="_blank"]; pause for loading and incorporate timeout controls

Overview I'm seeking a more streamlined approach to managing link clicks that open new pages (such as target="_blank" anchor tags). By "handle," I mean: fetch the new page object wait for the new tab to load (with specified timeout) Steps to r ...

I have to make sure not to input any letters on my digipas device

There is a slight issue I am facing. Whenever I input a new transfer of 269 euros with the bank account number BE072750044-35066, a confirmation code is required. The code to be entered is 350269. https://i.stack.imgur.com/YVkPc.png The digits 350 corres ...

Enhance React form rendering efficiency

Is there a way to improve the rendering of a 'form' component when a key is pressed? Any suggestions on how to optimize this process? const Example = () => { const [inputForm, setInputForm] = useState(''); const inputHandler = e ...

What are some effective methods for handling error objects in REST API services?

Encountered an error object: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'root'@'localhost' (using password: YES) Type of (err): Object Now, I am looking to pass this object to another web service (REST API) What content ty ...