What is the best way to add a new key to a .json object using JavaScript?

I am working with a hi.json file that contains an object. In my JavaScript code, I import this JSON file like so:

var obj = require("hi.json");

Now, I need to figure out how to write data into the JSON file programmatically using JavaScript. Is it possible to do something like this?

obj["key"] = "value";
// This change should also be saved in hi.json

Answer №1

Is it possible to write to a JSON file using JavaScript?

One way to achieve this is by utilizing the a element, adding a download attribute, and constructing a data URI

var data = require("example.json");

data["key"] = "value";
// Desired save operation

var link = document.createElement("a");
link.download = "example.json";
link.href = "data:application/json;charset=utf-8," + JSON.stringify(data);
document.body.appendChild(link);
link.click();

    var data = {
        "key": "undefined"
    };

    data["key"] = "value";
    // Desired save operation

    var link = document.createElement("a");
    link.download = "example.json";
    link.href = "data:application/json;charset=utf-8," + JSON.stringify(data);
    document.body.appendChild(link);
    link.click();

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

Acquiring mapping information through JSON data retrieval

Overview : Each levelNum has three corresponding dropdowns. For example, the dropdown for levelNum2 includes (Department-Unit-1, Department-Unit-2 & Department-Unit-3), levelNum3 includes (Division-Unit-1 & Division-Unit-2), and levelNum4 includes ...

What steps do I need to take in order to develop a custom interactive analyzer game using html/css

Hello there, I am on a mission to develop a mobile-friendly version of an analyzer game that I came across on this link - . The current version of the game is built using flash. My goal is to be able to easily customize the colors and images to fit differ ...

Display the page for 10 seconds continuously in a loop

I am currently developing a Node JS guessing game where data is collected on the back-end and sent to the front-end to start the game. The data consists of 10 levels, allowing the game to operate on a single page. Each level lasts for 10 seconds. Once the ...

Troubleshooting problem with video recording functionality using HTML 5 media streams

My HTML 5 code for video recording and uploading is encountering a JavaScript error when the start button is clicked. The error messages I am receiving are: "TypeError: webcamstream.record is not a function streamRecorder = webcamstream.record();" "TypeE ...

What is the best way to consistently resize elements to the same pixel value, like "10px", using jquery-ui?

Is there a method to consistently resize a div element by a specific pixel value each time, such as "10px"? I am attempting to achieve this using jquery-ui, where I can resize the element but desire to resize it consistently by a set pixel value. $(child ...

Tips for automatically resizing a canvas to fit the content within a scrollable container?

I have integrated PDF JS into my Vue3 project to overlay a <canvas id="draw_canvas"> on the rendered pdf document. This allows me to draw rectangles programmatically over the pdf, serving as markers for specific areas. The rendering proces ...

Zeroclipboard will fail to copy the text

I seem to be encountering an issue with the Zeroclipboard system. I suspect there might be an error in my code. Even though it indicates that the content has been copied, it actually hasn't been. The code I am currently using is as follows: <scri ...

What is the best way to increase dates in javascript?

I am working with a datetimepicker that has date and time format. I need to be able to add a specific number of days to the selected datetime. The datetime input will be selected from the datetimepicker input datetime = Friday, October 23rd 2015, 12:00:0 ...

What is the process for retrieving and utilizing the length of a value in an associative array?

I am currently attempting to retrieve the length of a value in an associated array as shown below. Ultimately, I am aiming to modify styles for each individual value. Does anyone have a solution for this issue? const shopLists = [ { genre: 'aaa&a ...

Struggling with serving static content on NodeJS using Express.js

I set up a basic NodeJS and Express server on my development machine running Windows 10. var express = require('express'); var app = express(); app.use(express.static('app')); app.use('/bower_components', express.static(&apo ...

Is the JQuery dropdown menu closing "instantly" upon clicking?

Whenever I tap on the "hamburger icon" in mobile view, the mobile navigation drops down but then quickly slides back up. The code responsible for this behavior is unfamiliar to me, so any assistance would be greatly appreciated. The code I am currently wo ...

Is it possible to create a cross-sectional view of a lens using the HTML5 canvas element?

I am interested in creating a visual representation of the cross section of a lens element. Typically, these elements consist of one or two circular surfaces (front and back) with a rim of arbitrary shape. My goal is to simply connect the front and back su ...

Can the ES2016 Proxy be used to intercept the "typeof" operation?

Can a handler property be defined to intercept typeof proxyObject? It is not mentioned in any of the traps listed on Mozilla. ...

Enhancing the visual appeal of a standard jQuery slider with thumbnails

Recently, I incorporated the Basic jQuery slider into my website, which can be found at . As a novice in jQuery but well-versed in HTML and CSS, I have managed to make it work seamlessly on my site. However, I am curious to know if there is a way to displa ...

What causes Chrome Extension Images to appear broken when they are inserted into the DOM?

Currently working on a Chrome extension, I am attempting to insert a div with a background image into the DOM using a content script. The CSS is loading correctly, and upon inspecting the Developer Tools, the image URL appears to be correct. $('.clos ...

What is the best way to retrieve information from a form that is coded within inner HTML?

I need to extract data from the text fields in my code. How can I do that? Here is my JavaScript function that adds a new form every time the add button is clicked: function elementAppender() { if (count <= 5) { let element = docum ...

Stop images from appearing transparent when placed inside a transparent div

My issue is clearly visible in this image: The div element is transparent and affecting the images inside it. Below is my HTML code: <div id="cselect" style="position: absolute; top: 99px; left: 37px; display: block;"> <div class="cnvptr"> ...

Leveraging real-time geographical location data for a weather widget with OpenWeatherAPI integration

My goal is to incorporate the current geolocation feature into a weather widget that I am developing. At the moment, I can only show data from cities based on an external source. My coding knowledge is quite limited. I am not a professional in this field, ...

Ways to split images and text in list items using CSS

Can the text be formatted in a specific location on the page, separate from the image and heading? This is the HTML code I am currently using: <div class="tab-pane container fade" id="environmental"> <div class="row"> <div class="c ...

Can AJAX function properly when the server-side code is hosted on a separate domain?

After opening Firefox's scratchpad and inputting the following code... function ajaxRequest() { var xmlhttp; var domainName = location.host; var url = 'http://leke.dyndns.org/cgi/dn2ipa/resolve-dns.py?domainName='; url = url + domainName + ...