Making changes to a JSON file using JavaScript

Hello everyone, I am a beginner in Javascript and have successfully created a system that allows me to search and filter users in my data.json file. However, I am now looking to develop an application that can add users to the data.json file. Any advice or guidance on how to achieve this would be greatly appreciated. Thank you in advance, Benjamin

HTML:

<html lang="en">
    <head>
        <link rel="Stylesheet" href="style.css">
        <script src="main.js"></script>
    </head>
    <body>
        <input class="name" placeholder="name">
        <input class="email" placeholder="email">
        <button class="submit">Add User</button>
    </body>
</html>

JSON:

[
  {
      "id": 1,
      "name": "Leanne Gr",
      "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3162585f5254435471504143585d1f53584b">[email protected]</a>"
  }
]

Answer №1

If you're looking to accomplish this task, consider utilizing the npm package

browserify-fs

This package can assist you in achieving your goal. Upon installation, you will be able to make use of the fileSystem.writeFile() function:

const fileSystem = require("browserify-fs")

const client = {
 "Name": "John Doe",
 "Mail": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b5d8d4dcd9f5d2d8d4dcd99bd6dad8">[email protected]</a>"
}
const data = JSON.stringify(client)

fileSystem.writeFile("./data.json", data, err=>{
 if(err){
   console.log("Error writing file" ,err)
 } else {
   console.log('JSON data is written to the file successfully')
 }
})

Answer №2

To achieve this functionality, you can utilize XMLHttpRequest requests. However, it is essential to have a server in place to host your JSON data.

If needed, you can set up a local server using the json-server npm package to act as your JSON server

In summary, the process requires a server and the use of XMLHttpRequest through Javascript for editing purposes

Alternatively, utilizing a Server Side programming language such as PHP is recommended

It's important to note that Javascript is a Client Side programming language

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

An error message is displayed when attempting to retrieve a json response

After implementing my flask app, I noticed that the following code snippet is being returned: return json.dumps({'status': 'OK','url': 'www.blahg.com'}) Upon inspecting my javascript code, I found it to be structur ...

Collision detection in Physisjs with Three.js PointerLockControls is an essential feature for creating

I am currently working on a project using Three.js with PointerLockControls. My goal is to implement collision detection for the player in order to enhance the overall experience. To achieve this, I have created a new Physijs cylinder object and passed it ...

Tips for creating multiple entries in JSON format

I'm facing an issue where each time I try to save a new RSS record to a JSON file, it ends up overwriting the previous one. How can I store multiple RSS records in the same file without losing any data? private void saveJSONtoFile(String jsonString) ...

The AJAX request encountered an error due to an Unexpected End of JSON Input

My AJAX code is encountering an error message. parsererror (index):75 SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at Nb (jquery.min.js:4) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js: ...

Combining Material UI with React Form Hook to handle multiple checkboxes with pre-selected defaults

I am working on creating a form with grouped checkboxes using react-form-hook and Material UI. The checkboxes are generated dynamically through an HTTP Request. I am aiming to set the default values by providing an array of object IDs: defaultValues: { ...

Saving JSON data into an array using Excel VBA

I have experimented with using an API to retrieve information from Yahoo Finance. Below is the custom UDF that I developed: Sub Test() '1 >> High & 2 >> Close MsgBox YahooHigh("GOOG", "2019-07-18", 1) MsgBox YahooHigh("GOOG", "2019-07 ...

PHP Implementing real-time dynamic categories

I am working on a project where there are multiple items listed with unique IDs. Each item has corresponding data with the same ID. I want to use JQuery, JScript, and PHP to display options based on the ID of the selected item in real-time. Below is a snip ...

Tips on handling multiple text field validation in material-ui for react?

Currently, I am working on developing a form using Material-UI and React.js where I need to validate two TextField components. My goal is to apply the same error and textHelper props to both TextFields. Below is a snippet of my code for reference. Any sugg ...

When a function is passed as an argument in Typescript, it may return the window object instead of the constructor

I'm still getting the hang of typescript, and I've come across a situation where a function inside a Class constructor is calling another function, but when trying to access this within sayHelloAgain(), it returns the window object instead. With ...

Problems Arising with Javascript Animation Functionality

I've created a script for an interactive "reel" that moves up or down when clicking on specific arrow buttons. However, I'm encountering two issues: 1) The up arrow causes it to move downward, while the down arrow moves it upward. 2) After exe ...

Download the browser version of UglifyJS 2 now

Is there a way to download the browser version of UglifyJS 2 without having to build it myself? I'm running into issues with the manual installation. I used npm to install uglify-js, but I can't seem to find where to execute the uglifyjs --self ...

Tips on assigning a value to a dynamically generated drop-down element

I used arrays of strings to populate drop-down menus. Is there a way to automatically set the value of each option to match the text content? el.value = opt; seems to be ineffective. var validCoursesKeys = ['opt 1','opt 2','opt ...

Analyzing and combining two JSON outputs by merging them using a specific key for comparison

json data1: { "ID": "7283949-4658-3i93899-2bb1-36748", "Name": "terra01-dc-domain" }, { "ID": "833bjhds949-42658-3idbj46-2bb1-33bsj", "Name": ...

What are effective ways to eliminate cross-origin request restrictions in Chrome?

Just starting out with angular and trying to incorporate a templateUrl in an angular directive. However, when attempting to view the local html file in the browser, I encounter the following errors --> XMLHttpRequest cannot load file:///Users/suparnade ...

A JavaScript function written without the use of curly braces

What makes a function good is how it is declared: export declare class SOMETHING implements OnDestroy { sayHello() { // some code to say hello } } However, while exploring the node_modules (specifically in angular material), I stumbled up ...

How can I ensure that the appropriate 'this' is accessed within a callback function for an AJAX request?

When working with a callback function, I am having trouble accessing this. Instead, it seems to be pointing to the AJAX object rather than the object that initially invoked the onClickEmail function. I attempted to store a reference in a variable called th ...

"Encountering an undefined error when making an AngularJS $http post request and receiving a

I am working on retrieving a specific value from the server side by passing a variable from the front-end (AngularJS javascript) to the backend (PHP) using $http. Once the server side (PHP) receives the value from the front-end, it executes an SQL query to ...

Can any function be used to define the path in ExpressJS when setting up GET routes?

I am currently working on developing a web application using node.js. However, I have encountered an issue when trying to use special characters in my navigation path, resulting in the error message "Cannot get /contest". In order to resolve this problem ...

Utilizing Flask for analyzing characteristics of text presented in JavaScript

My current variables consist of: myfruits = ['Apple', 'Banana', 'Lemon'] havefruit = [True, True, False] If the user input changes the values in havefruit, I need to implement JavaScript in my HTML file to display the entrie ...

Syntax for private members in ES6 classes

I'm curious to know the most efficient way to declare private members within ES6 classes. In simpler terms, what is the best practice for implementing: function MyClass() { var privateFunction = function() { return 0; }; this.publicFuncti ...