This answer is assuming that you are working under Node.js.

As I understand your problem you need to solve a few different programming questions.

  1. read and write a .json file

    const fs = require("fs");
    let usersjson = fs.readFileSync("users.json","utf-8");
    
  2. transform a json string into a javascript array

    let users = JSON.parse(usersjson);
    
  3. append an object to an array

    users.push(obj);
    
  4. transform back the array into a json string

    usersjson = JSON.stringify(users);
    
  5. save the json file

    fs.writeFileSync("users.json",usersjson,"utf-8");
    
Answer from PA. on Stack Overflow
🌐
Reddit
reddit.com › r/javascript › append a json file correclty
r/javascript on Reddit: Append a JSON file correclty
December 6, 2017 -

Hello.

I try to write on a JSON file, but this is what I got :

https://hastebin.com/lilomarede.json

As you can see, the id5 is complelty out of the JSON file.

I tried to use bizarre stuff like this (my actual code):

https://hastebin.com/olehohomoy.js

var punJson = "," + (punJson[punId] = { message: punMessage });

wich punID and punMessage are both values I get just before this little piece of code.

I tried to do

var punJson = "," + (punJson[punId] = { message: punJson[punMessage] });

Obviously, this dosen't work.

I got the error

TypeError : Cannot set property 'id5' of undefined

Any ideas ?

Discussions

How to add data to a JSON file in JavaScript?
The specifics can vary slightly ... your JavaScript code is running (Node.js server-side versus client-side in a browser). On a Node.js server, you have the filesystem (fs) module available to read from and write to files directly. Here’s how you can add data to a JSON ... More on designgurus.io
🌐 designgurus.io
1
10
June 24, 2024
Append an object to an existing JSON file
I’m relatively new to JS. I am working on a simple webpage which gets an input from user and manipulates it, and finally returns it as an object. What I want is, to append my output objects to my existing .json file, each time user submits the form. I’ve googled it. More on forum.freecodecamp.org
🌐 forum.freecodecamp.org
0
0
April 18, 2024
javascript - How do I add to an existing json file in node.js - Stack Overflow
Append file creates file if does not exist. But ,if you want to append JSON data first you read the data and after that you could overwrite that data. More on stackoverflow.com
🌐 stackoverflow.com
javascript - Write / add data in JSON file using Node.js - Stack Overflow
the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. More on stackoverflow.com
🌐 stackoverflow.com
April 26, 2016
🌐
Educative
educative.io › answers › how-to-add-data-to-a-json-file-in-javascript
How to add data to a JSON file in JavaScript
{ "users": [ { "name": "John Doe", ... Johnson", "email": "bob.johnson@example.com" } ] } ... Line 1: Import the fs module for reading and writing into the file....
🌐
GeeksforGeeks
geeksforgeeks.org › node.js › how-to-add-data-in-json-file-using-node-js
How to Add Data in JSON File using Node.js ? - GeeksforGeeks
July 23, 2025 - Node.js has an in-built module named fs, which stands for File System and enables the user to interact with the file system in a modeled way. To use it, type the code below in your server program. ... We can start by creating a JSON file, which will contain an id, a name and a city for this example.Note that you can have as many key-value pairs as you want, but we are using three here for a start.
🌐
freeCodeCamp
forum.freecodecamp.org › javascript
Append an object to an existing JSON file - JavaScript - The freeCodeCamp Forum
April 18, 2024 - I’m relatively new to JS. I am working on a simple webpage which gets an input from user and manipulates it, and finally returns it as an object. What I want is, to append my output objects to my existing .json file, ea…
Find elsewhere
Top answer
1 of 9
602

If this JSON file won't become too big over time, you should try:

  1. Create a JavaScript object with the table array in it

    var obj = {
       table: []
    };
    
  2. Add some data to it, for example:

    obj.table.push({id: 1, square:2});
    
  3. Convert it from an object to a string with JSON.stringify

    var json = JSON.stringify(obj);
    
  4. Use fs to write the file to disk

    var fs = require('fs');
    fs.writeFile('myjsonfile.json', json, 'utf8', callback);
    
  5. If you want to append it, read the JSON file and convert it back to an object

    fs.readFile('myjsonfile.json', 'utf8', function readFileCallback(err, data){
        if (err){
            console.log(err);
        } else {
        obj = JSON.parse(data); //now it an object
        obj.table.push({id: 2, square:3}); //add some data
        json = JSON.stringify(obj); //convert it back to json
        fs.writeFile('myjsonfile.json', json, 'utf8', callback); // write it back 
    }});
    

This will work for data that is up to 100 MB effectively. Over this limit, you should use a database engine.

UPDATE:

Create a function which returns the current date (year+month+day) as a string. Create the file named this string + .json. the fs module has a function which can check for file existence named fs.stat(path, callback). With this, you can check if the file exists. If it exists, use the read function if it's not, use the create function. Use the date string as the path cuz the file will be named as the today date + .json. the callback will contain a stats object which will be null if the file does not exist.

2 of 9
55

Please try the following program. You might be expecting this output.

var fs = require('fs');

var data = {}
data.table = []
for (i=0; i <26 ; i++){
   var obj = {
       id: i,
       square: i * i
   }
   data.table.push(obj)
}
fs.writeFile ("input.json", JSON.stringify(data), function(err) {
    if (err) throw err;
    console.log('complete');
    }
);

Save this program in a javascript file, say, square.js.

Then run the program from command prompt using the command node square.js

What it does is, simply overwriting the existing file with new set of data, every time you execute the command.

Happy Coding.

🌐
GitHub
github.com › jaxgeller › append-json-file
GitHub - jaxgeller/append-json-file: Append to a json file
You need to append to a json file, but sometimes it hasn't been created yet.
Starred by 4 users
Forked by 3 users
Languages   JavaScript 100.0% | JavaScript 100.0%
🌐
Evdokimovm
evdokimovm.github.io › javascript › nodejs › 2016 › 11 › 11 › write-data-to-local-json-file-using-nodejs.html
Write Data to Local JSON File using Node.js
November 11, 2016 - Now arrayOfObjects variable contains a object from users.json file: console.log(arrayOfObjects) // Output: { users: [] } Now we can write the data into an users array using the push() method is as follows: var fs = require('fs') fs.readFile('./users.json', 'utf-8', function(err, data) { if (err) throw err var arrayOfObjects = JSON.parse(data) arrayOfObjects.users.push({ name: "Mikhail", age: 24 }) console.log(arrayOfObjects) }) ... You can appended any objects to users array.
🌐
Reddit
reddit.com › r/learnjavascript › how do i append to an array inside a json file in node?
r/learnjavascript on Reddit: How do I append to an array inside a json file in node?
December 26, 2022 -

I’m working on a chat client and server to learn about API’s and now I need to write the messages submitted by users into the master chat log (a json file with a messages array inside of it). I have been searching for different approaches and they all error out somehow. I’m using node and express for routing if that helps.

tldr; how should one append an object to an array inside a json file using node.

edit: I’ve taken carcigenocate’s advice. I open the file, make the changes in memory, then write to the file and reload it to reflect changes. I am still open to improvements on this design!

Top answer
1 of 2
4

if you are using jQuery's getJSON or parseJSON(), you have a javascript object you can manipulate. for example:

$.getJSON( "/test.json", function( data ) {
  // now data is JSON converted to an object / array for you to use.
  alert( data[1].cast ) // Tim Robbins, Morgan Freeman, Bob Gunton

  var newMovie = {cast:'Jack Nicholson', director:...} // a new movie object

  // add a new movie to the set
  data.push(newMovie);      
});

All you have to do now is save the file. You can use jQuery.post() to send the file back to the server to save it for you.

Update: Posting an example

//inside getJSON()

var newData = JSON.stringify(data);
jQuery.post('http://example.com/saveJson.php', {
    newData: newData
}, function(response){
    // response could contain the url of the newly saved file
})

On your server, example using PHP

$updatedData = $_POST['newData'];
// please validate the data you are expecting for security
file_put_contents('path/to/thefile.json', $updatedData);
//return the url to the saved file
2 of 2
-1
<html>
<head>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
    <?php
        $str = file_get_contents('data.json');//get contents of your json file and store it in a string
        $arr = json_decode($str, true);//decode it
         $arrne['name'] = "sadaadad";
         $arrne['password'] = "sadaadad";
         $arrne['nickname'] = "sadaadad";
         array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
         $str = json_encode($arr);
        //now send evrything to ur data.json file using folowing code
         if (json_decode($str) != null)
           {
             $file = fopen('data.json','w');
             fwrite($file, $str);
             fclose($file);
           }
           else
           {
             //  invalid JSON, handle the error 
           }

        ?>
    <form method=>
</body>

data.json

{  
  "employees":[  
  {  
     "email":"11BD1A05G9",
     "password":"INTRODUCTION TO ANALYTICS",
     "nickname":4
  },
  {  
     "email":"Betty",
     "password":"Layers",
     "nickname":4
  },
  {  
     "email":"Carl",
     "password":"Louis",
     "nickname":4
  },
  {  
     "name":"sadaadad",
     "password":"sadaadad",
     "nickname":"sadaadad"
  },
  {  
     "name":"sadaadad",
     "password":"sadaadad",
     "nickname":"sadaadad"
  },
  {  
     "name":"sadaadad",
     "password":"sadaadad",
     "nickname":"sadaadad"
  }
   ]
}
🌐
Quora
quora.com › I-want-to-add-a-new-JSON-object-to-the-already-existing-JSON-Array-What-are-some-suggestions
I want to add a new JSON object to the already existing JSON Array. What are some suggestions? - Quora
Answer (1 of 5): Simply use push method of Arrays. [code]var data = [ { name: "Pawan" }, { name: "Goku" }, { name: "Naruto" } ]; var obj = { name: "Light" }; data.push(obj); console.log(data); /* 0:{name:"Pawan"} 1:{name: "Goku"} 2:{name: "Naruto"} ...
🌐
TestMu AI Community
community.testmuai.com › ask a question
Appending Data to JSON File in Node.js Without Overwriting - Ask a Question - TestMu AI Community
March 9, 2025 - How can I use Node.js to write JSON to a file while ensuring that new data is appended to the existing content instead of overwriting it? I want to generate a JSON file that stores an array of objects, each containing an ID and its square value. If the file already exists, new elements should ...
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-how-to-add-an-element-to-a-json-object
How to Add an Element to a JSON Object using JavaScript? | GeeksforGeeks
August 27, 2024 - In JavaScript to add an element to a JSON object by simply assigning a value to a new key.
🌐
ArduinoJson
arduinojson.org › version 6 › how to's › how to append a json object to a file?
How to append a JSON object to a file? | ArduinoJson 6
DynamicJsonDocument doc(8192); // Read the file File file = SPIFFS.open("/southpath.json", "r"); deserializeJson(doc, file); file.close(); // Append new element JsonObject obj = doc.createNestedObject(); obj["first_name"] = "Kenny"; obj["last_name"] = "McCormick"; // Write the file file = SPIFFS.open("/southpath.json", "w"); serializeJson(doc, file); file.close(); If you want to optimize the append-to-file scenario, you must change the format of the file.
🌐
GitHub
github.com › jprichardson › node-jsonfile › issues › 67
Appending to an existing JSON file: · Issue #67 · jprichardson/node-jsonfile
October 1, 2016 - You switched accounts on another tab or window. Reload to refresh your session. ... var file = 'mods-installed.json' var obj = {name: 'JP'} jsonfile.writeFile(file, obj, {flag: 'a'}, function (err) { console.error(err) }) jsonfile.writeFile(file, obj, {flag: 'a'}, function (err) { console.error(err) })
Author   lndgalante