Manipulating a JSON File by Adding an Object

I have an object:

var obj = {
        name: "Sarah",
        age: "25",
        id: "[3]"
}

and I am looking to add it to the existing list in "people.json":

[
  {    
    "name": "John",
    "age": "30",
    "id": [0]
  },
  {    
    "name": "Emma",
    "age": "28",
    "id": [1]
  }
]

Any suggestions on how I can achieve this? Thank you!

Answer №1

When working with Node.js, the following steps can help you tackle your programming questions.

Firstly, you'll need to read and write a .json file using the code snippet below:

const fs = require("fs");
let usersjson = fs.readFileSync("users.json","utf-8");

Next, you'll want to transform a json string into a JavaScript array like so:

let users = JSON.parse(usersjson);

After that, you can append an object to an array using the following line of code:

users.push(obj);

To transform the updated array back into a json string, use this piece of code:

usersjson = JSON.stringify(users);

Finally, don't forget to save the modified json file by executing the following command:

fs.writeFileSync("users.json",usersjson,"utf-8");

Answer №2

If your script is executing in the browser and users.json serves as an output file, chances are you can retrieve its contents easily.

Utilize the push() method.

Be mindful of the missing commas within your objects.

var obj = {
        username: "James",
        surname: "Brandon",
        id: "[2]"
};

var users = [
  {    
    "username": "Andy",
    "surname": "Thompson",
    "id": [0]
  },
  {    
    "username": "Moe",
    "surname": "Brown",
    "id": [1]
  }
];

users.push(obj);
console.log( JSON.stringify(users) );

With the updated array of objects in hand, consider uploading it to the server (refer to this question) or providing a download option for the user (see this other question).

It's worth noting that modifying a file on the server directly from the client side is not feasible. Similarly, saving files directly to the client's filesystem is not achievable.

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

I am interested in utilizing Maven and paulhammant (Selenium_java) to input text into a textefield

When attempting to write in the text field using selenium, I encountered an error stating "unexpected identifier". Any assistance with this issue would be appreciated. See image for more details ...

Leveraging the power of AJAX, PHP, and JavaScript to display numerous status updates throughout an extended operation

It has come to my understanding that when using PHP, it is not feasible to send messages to the DOM using AJAX as the entire script must finish executing before the response becomes available. This leaves me with two possible solutions: Break down the le ...

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

Display items in a visual format when they're contained within a JSON or object with NativeScript

Here is a snippet of JSON data: { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "pharmacy_id": "011E752345553380ABC13FFA163ECD15", "pharmacy_name": "Pharmacy", "lastUpdated": "2019 ...

What is the best way to dynamically validate the fields and generate an array?

Currently in my Angular application, I've successfully implemented a pivot table using pivot.js. Now, I am faced with the task of loading all the indexes from elastic search whenever the user switches the index. Once the index is changed, the corresp ...

Appear and disappear div

I am seeking to achieve a specific goal: I want to fade in a div with text after a certain number of seconds, then fade it out. I also want to repeat this process for 4 other divs, ensuring that they do not interfere with each other by appearing while the ...

Bring NavLinks from a separate class into the NavBar Class in a React application

Hello! I am new to React and I am currently working on creating a navbar component using materialize css. I have separate classes for loggedinlinks and loggedoutlinks, but when I include them in my Navbar class and run the application, the links are not ap ...

The product has been taken out of the cart, yet it has not been reinserted into the cart

The product disappears from the cart after clicking on Add to Cart, but it doesn't reappear when clicked again. //function for adding only one item to cart document.getElementById('btn1').onclick = function() { addItemToCart() }; fun ...

Conversation with form component in angular2

I am currently using ng2-bootstrap-modal. For adding a sample form to the example Confirm Dialog, check out ng2-bootstrap-modal. To change the template: <div class="modal-dialog"> <div class="modal-content"> <form [formGroup]="login ...

Making a chain of multiple AJAX requests using jQuery

My current challenge involves retrieving data from select options on a website using JavaScript. Specifically, I am trying to obtain a list of zones within my country from a website that has this information. The issue I am facing is the hierarchical disp ...

Guide on utilizing selenium webdriver for link clicking

Is there a way to utilize selenium webdriver in order to retrieve all links from a page that contain the attribute a[href*=/simulation/form/], and proceed to open and close each one? Although I attempted the code provided below, I encountered the error me ...

Using Angular to store checkbox values in an array

I'm currently developing a feature that involves generating checkboxes for each input based on the number of passengers. My goal is to capture and associate the value of each checkbox with the corresponding input. Ultimately, I aim to store these valu ...

How to Use an Object Created from a Different Class in TypeScript

Scenario In the development process, I am using an auth.service.ts. This service is responsible for fetching user information from the database upon login. The retrieved data is then used to create a new user object. Here is a snippet of the code: user: ...

Contact the Admin via socket.io (client-client communication)

How can I use socket.io to send messages to a specific client? I am trying to establish communication between a User and an Admin. Below is the code I have written for this purpose: Server socket.on('client', (data) => { console.log(data ...

How can we stop self shadowed faces from being illuminated?

Currently, I am working on creating a city scene in Three.js and experimenting with lighting and shadows. Specifically, I am focusing on a single building that was modeled in 3DS Max, then exported to OBJ format, and converted using a Python converter thro ...

What is the best way to incorporate an image that appears when a user clicks on a

My goal is to dynamically place an image exactly where a user clicks on the webpage. Currently, I have the following code, but it only adds the image at the top and continues to do so repeatedly...not appearing at the clicked location. <html> ...

Using Electron to redirect to a different HTML file while passing GET variables

I am currently working on developing an Electron app. Within the project files, for example, I have app.html. My goal is to send GET variables like ?id=54&q=asd to the receiver.html, where I can then retrieve these id and q variables. As we all know, ...

Adjusting the height of a textarea within a table

My textarea's height is supposed to be 500%, but it's not changing. I suspect that being inside a table might have something to do with the issue, but I'm unsure of what needs to be adjusted to set the height correctly. Surprisingly, the wid ...

Styling Elements with CSS Containers

Currently, I am going through a web development project on YouTube where I am constructing a JavaScript clock. It seems that by creating a container and a child element, I can use absolute and relative positioning. However, one thing that confuses me is w ...

Copy values of multiple input fields to clipboard on click

I have a collection of buttons in my Library, each with different text that I want to copy when clicked function copyTextToClipboard(id) { var textElement = document.getElementById(id); textElement.select(); navigator.clipboard.writeText(textElement. ...