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

Extracting JSON data from a column in Presto

In my Presto table, there is a specific structure that I am trying to achieve. Specific Date Specific Rates 1/1/2022 {"USD":"725.275","GBP":"29.275000000000002","CAD":"0.713352"} 1/2/202 ...

angular2 angular-entity directive

I have developed a component that accepts a template: export class TemplateParamComponent implements OnInit { @Input() items: Array<any>; @Input() template: TemplateRef<any>; } Here is the HTML code: <template #defaultTemplate le ...

What is the method for creating a function using the const keyword in JavaScript?

I trust you are doing well. Recently, I have embarked on a coding journey and encountered an interesting challenge. The task requires me to create a function that outputs specific weather conditions for different countries to the console: The weather in ...

Pull the Bootstrap radio value from hyperlink buttons

Is anyone else having trouble retrieving values of radio buttons using jQuery? Here are the radio buttons in question: <div class="input-group"> <div id="radioBtn" class="btn-group"> <a class="btn btn-warning radio-selector btn ...

Using jQuery to loop through a collection

I have a page that displays a list of posts. When a user clicks on the show comments button for a particular post, the comments associated with that post become visible. This functionality is achieved by using this and then searching based on the click loc ...

Exploring the Structure of Trees using JavaScript

Here are my terms: var terms = [ { id: 1, name: "Name 1", parent: null }, { id: 2, name: "Name 2", parent: 6 }, { id: 3, name: "Name 3", parent: null }, { id: 4, name: "Name 4", parent: 2}, { id: 5, name: "Name 5", ...

Apply a see-through overlay onto the YouTube player and prevent the use of the right-click function

.wrapper-noaction { position: absolute; margin-top: -558px; width: 100%; height: 100%; border: 1px solid red; } .video-stat { width: 94%; margin: 0 auto; } .player-control { background: rgba(0, 0, 0, 0.8); border: 1px ...

Error: The code is trying to access the property 'string' of an undefined variable. To fix this issue, make sure to

I encountered an issue after installing the https://github.com/yuanyan/boron library. The error message I received is: TypeError: Cannot read property 'string' of undefined Error details: push../node_modules/boron/modalFactory.js.module.expor ...

Aws Glue encountering issues with parsing nested JSON data properly

I received an API response that has this format. I need to upload it to S3 and have AWS Glue Crawler crawl it. However, the Glue Crawler is creating one row with multiple columns instead of separate rows. I am wondering if the JSON structure from the API ...

Creating a JSON serialization tool

When considering developing a serializer for a language like ABAP where there isn't currently one available, what are the potential challenges and efforts required? Is it simply a matter of creating a text equivalent of an ABAP serializer or would mor ...

Get a webpage that generates a POST parameter through JavaScript and save it onto your device

After extensive research, I have hit a roadblock and desperately need help. My task involves downloading an HTML page by filling out a form with various data and submitting it to save the responses. Using Firebug, I can see that my data is sent over POST, ...

PHP script encountering difficulty inserting data into database when AJAX is utilized; functions flawlessly without AJAX

In my "user registration" file, there is a form with the following structure: <form action="" method="POST"> <label for="user" class="control-label">User </label> <input type="text" name="user" class="form-control" id="user" ...

Conceal the div element if the value is either undefined or empty in AngularJS

I am experiencing an issue where I get 2 different values when I use console.log($scope.variable). The values shown are undefined and ''. Based on this value, I need to hide a div. Here's what I have tried: <div ng-hide="$scope.variable ...

Converting JSON to an array using PHP

My dilemma lies with a JSON string that I am unable to access values from. $json_string : '{"05526":[{"name":"rapertuar","surname":"xyz","notes":[{"mat1":"59","eng2":"60"},{"mat2":"59","eng2":"60"}]}]}'; $content = file_get_contents($json_string ...

Using Jquery to input selected dropdown values into a text input field

Currently, I am facing some challenges in achieving this task. My goal is to have the selected option from a dropdown list called programs_dropdown added to a text field named programs_input, with the option values separated by commas. For example: php, j ...

Transforming JSON data into a Flutter model class

I have been struggling to convert my JSON data into a model class using the tool at . However, I am not achieving the desired result. Can anyone please offer assistance? Here is a snippet of my JSON data: [ { "Id": 0, "S ...

Utilizing Data Binding in D3.js

Why is the text "Hello" not appearing five times on the page as expected? index.html <html> <head> <title>Data Binding</title> </head> <body> <h1>D3.js</h1> <script src="https://d3js.o ...

Encountered a TypeError with mongoose: The function specified is not recognized as a valid function when attempting to create a new mongoose instance

I'm currently developing a web application using the MEAN stack, and I've encountered an issue with my mongoose instance that's giving me a headache. Let me share parts of my code: my route const express = require('express'); co ...

I am having trouble comprehending this specific type definition within a properly formatted JSON Schema

Exploring the definitions of Cats and Dogs within: { "Boxes": { "type":"object", "properties": { "Cats": {"type":["integer","null"]}, "Dogs": {"type":["integer","null"]} ...

What is the best way to align my clip-path's text with the center of the viewport and ensure that all of the clip-path's text is visible?

Check out my React component demo: https://codesandbox.io/s/epic-brown-osiq1. I am currently utilizing the values of viewBox, getBBox, and getBoundingClientRect() to perform calculations for positioning elements. At the moment, I have hardcoded some values ...