How to add new data to a JSON file with JavaScript

Currently, I am developing a discord bot that extracts responses from a JSON file. The structure of the JSON file is basic and looks like this:

"matt":
{
  "insults" : ["test 1", 
              "test 2", 
              "test 3", 
              "test 4"
             ]
},

My current focus is on creating a function that allows users to use the !addInsult command, followed by a string, which will then be added to the existing array.

The ideal process would go something like this:

User enters: !addInsult test 5. This action should modify the JSON object of insults under matt to look like this:

"matt":
{
   "insults" : ["test 1", 
                "test 2", 
                "test 3", 
                "test 4",
                "test 5"
               ]
},

By implementing this feature, it will enable my friends to contribute data to my bot without requiring manual intervention to update the JSON every time we want to add something new.

What would be the most effective approach to achieving this? I have heard of something called push, but I am unclear on how it operates.

This is what I have accomplished so far. I believe I am headed in the right direction, though not entirely confident:

The code snippet below is declared at the beginning of the script:

// contains the insults
var insults = require('./insults.json');

// retrieving insults from the user-specific JSON file
var insultsString = JSON.stringify(insults);
var json = JSON.parse(insultsString);

Here is the function responsible for appending the insults:

// command allowing users to add to the insult pool
function addInsultCommand(args, receivedMessage)
{
  // create an object containing information for the JSON file
  json["bot"].push(["test"]);

  receivedMessage.channel.send(json.matt.insults[0]);
}

Answer №1

Let's clear up a common misunderstanding: JavaScript does not have the capability to write to files directly.

In your situation, you are utilizing webpack, which allows you to use a loader to require the .json file. However, this method only functions when using the development server. When you distribute your code, the .json file will be encoded into your output bundle, rendering it inaccessible for modifying.

Remember that JavaScript cannot create files for you (unless it's local). To achieve your goal, you should take these steps:

1) Download the .json file from the web server without relying on a webpack loader.

2) Make any necessary modifications to the JSON data in memory.

3) Upload the updated JSON data back to the web server so it can generate the file for you.

Furthermore, I'm unable to trace your example code as you mention receivedMessage.channel.send without prior definition. Could this possibly involve discord integration? For clarity, kindly rephrase your question and provide a concise demonstration of the issue with reproducible test code.

Answer №2

When you use JSON.stringify, it transforms a JavaScript object into a JSON object. On the other hand, JSON.parse does the opposite by converting a JSON object back into a JavaScript object. If the insults.json file contains a JSON object, there is no need to convert it into a string. Simply use JSON.parse(insults) to change it into a JavaScript object.

In the addInsultCommand function, I'm unsure about your intentions with the args variable, so I'll set that aside for now and provide you with some steps to follow below.

1) Convert the JSON object (insults) into a JavaScript object.

2) Develop a function that accepts a JavaScript object and a receivedMessage (the insult to add), assigning it to the appropriate location in the JavaScript object.

3) Transform the JavaScript object into JSON format (using JSON.stringify) and update the content of insults.json with the revised value.

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

What could be causing the Uncaught TypeError error in ionic serve?

Every time I run the Ionic serve command, my project loads in the browser but unfortunately shows a couple of errors in the console. An error occurred: Uncaught TypeError: Cannot read property 'innerHTML' of null(…) Another issue appeared: Fa ...

Deconstructing and processing nested JSON objects on iOS

I've been dealing with nested JSON objects in iOS, but I'm having trouble parsing them. Can anyone lend a hand? I've tried several sources, but none have been helpful. The JSON file looks like this: { "taskList":[ { "taskId":1 ...

Having trouble receiving any ringing status in nextjs while utilizing the getstream SDK

I attempted to integrate the getstream video SDK for calling from the caller to the callee. While I can successfully create calls from the caller side, I am not receiving any status updates about the call on the callee side. Below are my codes for the cal ...

React Next.js failing to trigger useEffect hook on live application

Recently, in my Next.js/React application, some previously functional pages began to exhibit strange behavior. Specifically, certain Axios requests within a useEffect hook are no longer being sent at all. Additional Information: The problematic file is a ...

Incorporate data from a CSV file into an HTML table on the fly with JavaScript/jQuery

I have a CSV file that is generated dynamically by another vendor and I need to display it in an HTML table on my website. The challenge is that I must manipulate the data from the CSV to show corrected values in the table, only displaying products and not ...

Tips for creating a versatile text with javascript

I am attempting to achieve a similar result: <?php $url = 'http://www.mydomain.com/img/picture.jpg'; ?> <img src='<?php echo $url ?>' /> However, I would like to achieve this using javascript. It would look something ...

When transitioning to an object, Vue.js fails to refresh

My component contains an object called elements: elements: { id: { text: '', color: '', ... } To modify it, I use: <a-textarea autoFocus placeholder="text to include" :style="{ width: &ap ...

How can I transfer a particular data value from a div to JavaScript within Laravel 5.0?

Displaying separate square divs based on integers retrieved from the database. This is the front-end view. I want to pass the room ID (code) to a JavaScript function when clicking on these div elements. https://i.stack.imgur.com/aIYTr.png Below is my cur ...

Transmit a JSON object to the server using a JavaScript function

I am attempting to transmit a JSON object to a remote server but I am not receiving a success message. Can someone please help me identify what is incorrect in this code: function sendSMS(){ var input = '{"header":"****","****":*****,"****":"**** ...

Transform JSON Date to Datatables

"tgl_dok":{"date":"2018-07-02 00:00:00.000000","timezone_type":3,"timezone":"Europe\/Berlin"} JavaScript snippet using jQuery $(document).ready(function(){ $('#table').DataTable({ "paging": true, "lengthChange": true, "search ...

Having trouble with blurriness in the SVG image loading on three.js

Currently, I am using loadTexture (THREE.ImageUtils.loadTexture('/images/areaYellow.svg')) to load SVG images. However, when I zoom in on the image, it becomes blurred. Is there a way to load the image without this blurriness? I am currently work ...

Decoding JSON in MySQL: Handling Nested JSON within JSON

Struggling with utilizing the MySQL JSON functions to extract a value from a nested JSON string? Here's an example: { "SucceededAt": "2022-01-18T07:54:50.5548083Z", "PerformanceDuration": "1463", "Lat ...

Building a single page web application using TypeScript and webpack - a step-by-step guide

For a while now, I've been working on single page applications using Angular. However, I'm interested in creating a single page application without utilizing the entire framework. My goal is to have just one .html file and one javascript file, w ...

Top recommendation for parsing a single record from a JSON array

Currently I am fetching the result of a REST method (observable) which typically contains only one element. Although my code is functional and displaying the data, I keep getting an ERROR message in the browser console saying TypeError: Cannot read propert ...

Dealing with lag in Kendo Grid (Utilizing Kendo Grid, Angular JS, and Web API)

Query : I have integrated a Kendo Grid into my Angular JS HTML page. The data for the Kendo Grid is fetched from a remote service Web API. While paging through the Kendo Grid, it attempts to download a whopping 38 MB of content for every 10 records, taki ...

Struggling with the Nivo slider not loading properly?

Check out my personal website. I'm having an issue with my Nivo slider not displaying properly - it just keeps loading. Any ideas on why this is happening and how I can fix it? Below is the CSS I am using: #slider { position:relative; width: ...

Sending an array input to PHP

I am having trouble sending an array input to PHP via JavaScript. The posted array does not seem to be showing up in the controller when I try to print it. Here is the relevant code snippet: submitHandler: function(form) { $('input[name="val_prof ...

Generate a new dynamic page in ASP.NET C# eCommerce platform whenever a user posts their item

Currently, I am in the process of building a website similar to eBay where users can list their own items for sale. My main concern is ensuring that each time a user posts an item on our site, a new link or page will be automatically generated. The same go ...

Removing information from a database using the delete function

I'm currently facing an issue while trying to delete an item from the database using a button that calls a delete function. Everything seems to be working fine, and I can see the API call for deletion in the console. However, the req.body is coming up ...

The Boolean value retrieved from a NodeJS webservice behaves unexpectedly when incorporated into a test scenario

After calling a NodeJS webservice using the following code snippet: request({ url: "http://10.210.210.41:3001/trackable/lastPos", json: true }, function (error, response, body) { if (!error & ...