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
🌐
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....
Discussions

Append a JSON file correclty
Rewrite the whole file with the contents of the puns object would be the easiest. Otherwise, if you absolutely NEED to append it, make sure you remove the previous closing bracket so your new key will be in the same object, not outside of it. More on reddit.com
🌐 r/javascript
11
3
May 21, 2018
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 25, 2024
javascript - Write / add data in JSON file using Node.js - Stack Overflow
I would not suggest writing to file each time in the loop, instead construct the JSON object in the loop and write to file outside the loop. More on stackoverflow.com
🌐 stackoverflow.com
April 26, 2016
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
🌐
Reddit
reddit.com › r/javascript › append a json file correclty
r/javascript on Reddit: Append a JSON file correclty
May 21, 2018 -

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 ?

🌐
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. This solves that problem. var myJson = { name: { first: 'Jackson', last: 'Geller' } } // My file contains {dob: '9/27/1994'} var myFile = 'data.json' // Call -- creates file if it doesn't exist and appends appendjson(myJson, myFile, function() { console.log('done') }) /* output -- data.json { dob: '9/27/1994, name: { first: 'Jackson', last: 'Geller' } } */ npm install appendjson --save ·
Starred by 4 users
Forked by 3 users
Languages   JavaScript 100.0% | JavaScript 100.0%
🌐
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 - It is one of the easiest ways to ... with Node.js, refer ... To add data in JSON file using the node js we will be using the fs module in node js....
Find elsewhere
Top answer
1 of 9
606

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
57

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.

🌐
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…
🌐
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 - For append new content to users.json file we need to read the file and convert it contents to an JavaScript object using JSON.parse() method: var fs = require('fs') fs.readFile('./users.json', 'utf-8', function(err, data) { if (err) throw err var arrayOfObjects = JSON.parse(data) })
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"
  }
   ]
}
Top answer
1 of 2
5

Try this. Don't forget to define anchors array.

var data = fs.readFileSync('testOutput.json');
var json = JSON.parse(data);
json.push(...anchors);

fs.writeFile("testOutput.json", JSON.stringify(json))
2 of 2
0

I created two small functions to handle the data to append.

  1. the first function will: read data and convert JSON-string to JSON-array
  2. then we add the new data to the JSON-array
  3. we convert JSON-array to JSON-string and write it to the file

example: you want to add data { "title":" 2.0 Wireless " } to file my_data.json on the same folder root. just call append_data (file_path , data ) ,

it will append data in the JSON file, if the file existed . or it will create the file and add the data to it.

data = {  "title":"  2.0 Wireless " }
file_path = './my_data.json'
append_data (file_path , data )

the full code is here :

   const fs = require('fs');
   data = {  "title":"  2.0 Wireless " }
   file_path = './my_data.json'
   append_data (file_path , data )

   async function append_data (filename , data ) {

    if (fs.existsSync(filename)) {
        read_data = await readFile(filename)
        if (read_data == false) {
            console.log('not able to read file')
        }
        else {
            read_data.push(data)
            dataWrittenStatus = await writeFile(filename, read_data)
            if dataWrittenStatus == true {
              console.log('data added successfully')
            }
           else{
              console.log('data adding failed')
            }
        }
      else{
          dataWrittenStatus = await writeFile(filename, [data])
          if dataWrittenStatus == true {
              console.log('data added successfully')
          }
          else{
             console.log('data adding failed')
           }
      }
   }



    async function readFile  (filePath) {
      try {
        const data = await fs.promises.readFile(filePath, 'utf8')
        return JSON.parse(data)
      }
     catch(err) {
         return false;
      }
    }

    async function writeFile  (filename ,writedata) {
      try {
          await fs.promises.writeFile(filename, JSON.stringify(writedata,null, 4), 'utf8');
          return true
      }
      catch(err) {
          return false
      }
    }
🌐
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 - But we can make these datatypes as objects by using the new keyword. Below are the approaches to conditionally adding a me ... JavaScript Object Notation (JSON). It is a lightweight data transferring format. It is very easy to understand by human as well as machine.
🌐
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"} ...
🌐
UiPath Community
forum.uipath.com › help › studio
How to append JSON Object in another File - Studio - UiPath Community Forum
June 13, 2024 - Hi Team, I have two Json File , One for DEV and One for PROD, Basically i am trying to append “XYZ” from DEV JSON file to PROD file, Could you please help me here , Attached is the JSON files When ever new App code a…
🌐
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 ...
🌐
GitHub
gist.github.com › 4466866
Reading JSON file and append list options into element select · GitHub
Save internoma/4466866 to your computer and use it in GitHub Desktop. Download ZIP · Reading JSON file and append list options into element select · Raw · README.mdown · Lee un archivo json y añade la lista de opciones a un elemento select · Reading json file and append list options into element select ·
🌐
Stack Overflow
stackoverflow.com › questions › 41580278 › append-to-object-in-external-json-file-javascript
Append to object in external JSON file javascript - Stack Overflow
var urlList = require('./urlList.json'); app.get('/hello', function(req, res){ var cat = 5; catNumber = "number" + cat; url = urlList[catNumber]; request(url, function(error, response, html){ if(!error){ var $ = cheerio.load(html); var number; var json = { }; $('.content').filter(function(){ var data = $(this); title = data.children().first().text().trim(); json.number = url; }) } fs.writeFile('file.json', JSON.stringify(json, null, 4), function(err){ console.log('File successfully written!'); }) javascript · json · append ·