A guide on using Javascript to write information to a JSON file

Let's consider an example where we have a .JSON file with the following content:

[{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"}]

We are looking to add another object

{"nissan": "sentra", "color": "green"}
into this existing array in the .json file. This would update the file to look like:

[{"honda": "accord", "color": "red"},{"ford": "focus", "color": "black"},{"nissan": "sentra", "color": "green"}]

I am searching for information on how to use AJAX to write new data to a .json file and update it with additional data, as most resources focus on reading data using AJAX from a .json file. Any suggestions or guidance on this matter would be greatly appreciated!

Answer №1

It is important to have a clear understanding of what is meant by the term "JSON".

Sometimes, people misuse the term JSON when referring to a basic JavaScript object, like [{a: 1}], which in this case happens to be an array. If you want to add a new element to the array, simply use the push method, as shown below:

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

Alternatively, JSON can also describe a string encoded in JSON format, such as:

var json = '[{"a": 1}]';

Note the single quotation marks around the string, indicating it is not a JavaScript object. To convert this string into a JavaScript object, you would utilize the JSON.parse function:

var obj = JSON.parse(json);

After manipulating the object as needed, including using push, if you wish to transform it back into a JSON string, you can employ JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON also functions as a common data formatting tool for transmitting information to and from servers, typically through ajax requests. Ajax facilitates the retrieval of JSON-formatted data from a server, manipulation of said data, and submission of modified JSON data back to the server. When handling JSON responses obtained via ajax, remember to use JSON.parse prior to any manipulation, and then JSON.stringify before sending the data back.

The mention of a "JSON file" raises questions about its existence, source, and purpose. While browsers lack direct access to physical files on a device, they can manage and interact with JSON strings, JavaScript objects, and communicate with servers to handle JSON data storage. Clarifying whether you are working with a JSON-format string, a JavaScript object, or require interaction with server-stored JSON will guide your approach to handling and processing the data effectively.

Answer №2

In order to store JSON data locally, the JavaScript method JSON.stringify can be utilized to serialize a JS object. It's important to note that directly writing to a JSON file using only JavaScript is not possible. The alternative options for storing data include cookies or local storage.

var obj = {"toyota": "corolla", "color": "red"};
localStorage.setItem('myCar', JSON.stringify(obj));

To access the stored object later on:

var carObj = JSON.parse(localStorage.getItem('myCar'));

Answer №3

Unfortunately, as of September 2018, there is no cross-browser solution available for client-side file writing.

For instance: While in browsers like Chrome we currently have the ability to write files using FileSystemFileEntry.createWriter() through a client-side call, it is noted in the documentation that:

This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.


For IE (excluding MS Edge), ActiveX could be used, but this is limited to specific clients.

If you wish to update your JSON file across different browsers, you will need to utilize both server and client-side approaches.

The client-side script

On the client side, you can send a request to the server and then process the response from the server. Alternatively, you could also read a file using FileReader. Cross-browser file writing requires a server component (refer to the server section below).

var xhr = new XMLHttpRequest(),
    jsonArr,
    method = "GET",
    jsonRequestURL = "SOME_PATH/jsonFile/";

xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
    if(xhr.readyState == 4 && xhr.status == 200)
    {
        // Convert JSON into JavaScript object
        jsonArr = JSON.parse(xhr.responseText);

        // Add a new value:
        jsonArr.push({"nissan": "sentra", "color": "green"});

        // Send the updated JSON file to the server with a new request:
        xhr.open("POST", jsonRequestURL, true);
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        // Handle POST response if needed
        xhr.send("jsonTxt="+JSON.stringify(jsonArr));
        // Server handling required to write updated JSON to the file
    }
};
xhr.send(null);

Server-side scripts

Various servers can be utilized, but PHP and Node.js servers are specifically discussed here.

You can search for "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server, consider 000webhost.com, and for Node.js, check out this list.

PHP server-side script solution:

The PHP script for reading and writing from a JSON file:

<?php

// This PHP script must be located in "SOME_PATH/jsonFile/index.php"

$file = 'jsonFile.txt';

if($_SERVER['REQUEST_METHOD'] === 'POST')
{
    file_put_contents($file, $_POST["jsonTxt"]);
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
{
    echo file_get_contents($file);
}
?>

Node.js server-side script solution:

Note that Node.js involves a different approach compared to normal browser JavaScript. It's recommended to study introductory books before delving into Node.js development:

  • Learning Node: Moving to the Server-Side
  • Node.js Web Development: Server-side development

The Node.js script for reading and writing from a JSON file:

var http = require("http"),
    fs = require("fs"),
    port = 8080,
    pathToJSONFile = '/SOME_PATH/jsonFile.txt';

http.createServer(function(request, response)
{
    if(request.method == 'GET')
    {
        response.writeHead(200, {"Content-Type": "application/json"});
        response.write(fs.readFile(pathToJSONFile, 'utf8'));
        response.end();
    }
    else if(request.method == 'POST')
    {
        var body = [];

        request.on('data', function(chunk)
        {
            body.push(chunk);
        });

        request.on('end', function()
        {
            body = Buffer.concat(body).toString();
            var myJSONdata = body.split("=")[1];
            fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
        });
    }
}).listen(port);

Related links for Node.js:

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

Once an ng-repeat is completed, I must extract and retrieve the 'id' of a specific element

Is it possible to retrieve the 'id' of the comment I'm replying to and save it for an Ajax call? I can easily access other data with ng-model, but using value="{{this.id}}" in a hidden input doesn't seem to work like in JQuery. <scr ...

Stealthy access using the Facebook API log-in

I'm currently developing an app that features Facebook login functionality. I'm wondering if there's a way to keep a device authorized so that users don't have to go through the process of logging in with Facebook each time they use the ...

Utilizing Spring's REST Template for JSON data manipulation

Is there a tool available in Spring or any other open source platform that can automatically generate client-side code objects for complex JSON objects returned by a 3rd party RESTful webservice? In SOAP, I'm familiar with using wsdl2java in Apache C ...

Tips for efficiently awaiting outcomes from numerous asynchronous procedures enclosed within a for loop?

I am currently working on a search algorithm that goes through 3 different databases and displays the results. The basic structure of the code is as follows: for(type in ["player", "team", "event"]){ this.searchService.getSearchResult(type).toPromise ...

Utilizing VueJS to transfer information for constructing a pricing plan chart

This is my first experience with VueJS, so I would greatly appreciate any advice or alternative methods to solve the issue. You can view my progress so far here. I am working on creating a pricing plan table where users can explore four different payment ...

Issue encountered while installing npm via command line

Currently in the process of installing node on my Mac and encountering an error. I downloaded Node from the official website and executed the package, but I am still facing issues. Can anyone advise me on why this error is occurring when I attempt to run ...

How can one create a function that delays the execution of code until AJAX data is received

I developed a CKEditor plugin that fetches data via ajax to create RichCombo functionality. The plugin functions correctly, however, when there are multiple instances of the editor on a single page, each plugin ends up sending its own ajax request, leading ...

Bringing @angular/code into a directory that is not within an Angular project

Currently, I have an Angular 2 project folder with a separate service folder named "auth.service.ts" located outside of it. Within this service file, I am importing `Injectable` from `@angular/core`. However, due to the service being located outside of t ...

The Angular data table is encountering an issue as the dataStream.pipe function is not recognized

I'm currently working on setting up a table using Angular data table, but I've run into an issue related to the dataSource. I'm seeing an error message that says "dataStream.pipe is not a function", and I'm having trouble resolving it. ...

Having trouble with the Vuejs validation code not functioning correctly?

I need help with a JavaScript function that posts objects to the backend only if all items are numbers. Here is the code snippet I'm working with: var MyApp = new Vue({ el: '#my_element', data: { errors: [], ...

Utilizing asynchronous functions to assign a JSON dataset to a variable

Having an issue here! I've created a function to retrieve data from a local JSON file on my server. The problem is that the data is returned asynchronously, so when I try to set it to a variable for later use, it always ends up being undefined. I don& ...

Guide on how to use ajax to update items in a ListView on an asp.net web form

I have a listview and ajax set up in an asp.net web form. One section of the form displays comments that readers can rate positively or negatively. The issue is that these ratings are not updated unless the page is refreshed. Is there a way to dynamically ...

Issue with Material UI tool tip not closing upon clicking on an element is persistent

Check out this link for a material UI tooltip demo I have been experimenting with the material UI tooltip in the provided link. The tooltip pops up when hovering over the button, but it doesn't disappear when clicking on the button. Is this the defau ...

Load the page's content gradually, without needing to wait for all the content to be fully loaded

I am facing an issue with a webpage that displays 10 different items, each of which has a slow loading time. Currently, the entire page waits for all 10 items to fully load before displaying anything. I am interested in finding out if it is feasible to sh ...

Interacting with a 3D model using the mouse cursor in a three

After stumbling upon the three.js library recently, I've been spending several days experimenting with it. I am eager to incorporate a mouse event into my project similar to this example where the head of the skull follows the cursor. However, I want ...

New feature in jQuery inputmask enables placeholder text to be retained

I have integrated the inputmask feature from https://github.com/RobinHerbots/jquery.inputmask in my project, and I am applying the mask to all textboxes with the class "date". However, I am encountering a problem where if the user leaves one or more letter ...

Creating PDFs in iOS and Android using Ionic framework

Seeking assistance with resolving this issue. I have researched extensively on Google, jspdf, pdfmake.org, inappbrowser plugins, but have been unsuccessful in getting my Ionic project to function properly. The goal is to create a simple form that includes ...

In order for Javascript to continue, it must first wait for a request to be completed

I have a beginner question that's been on my mind. I'm currently working on creating a wrapper for an API and I need to authenticate to receive the access token for further requests (please note, the API doesn't use OAuth). Here is a simpli ...

Untangling a variety of data types in a JSON array using Swift

I need help decoding this JSON Object: { "result":[ { "rank":12, "user":{ "name":"bob","age":12 } }, { "1":[ ...

When the browser is not in the foreground, clicking on the Bootstrap datepicker with Selenium does not register

When you click on the input field <input id="dp1" class="span2" type="text" value="02-16-2012"> If the browser is in the background, the datepicker popup will not display. Even using javascript or jquery to click the input field does not show the ...