How to add a key/value pair to an existing json file?

The Json file would look some like this:

“data”: [

  "id": "1700148573403304137",
  "text": "Hi ! "

  "id": "1700147255322259501",
  "text": "Hello"


For the final I want to add something like:

“text2” : “Hi back!”
“text2”: “Hello back!”

What code do I have? First I bring the file like this:

import theData from “./thejsons/a.json” assert { type: “json” };
const dataMain =;

*** the text2 data I don’t have right away because it is running on an SetInverval() function… but everything time it runs I am catching in a variable… then, every time I get a value for the variable I try to write it in json file… but I am unable to write as an extra key/value pair…

this part of the setInterval() goes some like this:

console.log(newText); // ← this is good, as I am login new text each interval.

  fs.readFileSync("./thejsons/a.json", "utf-8");

    (dataMain.text2 = newText),  // <-- this is not working as it loads the text on the bottom of the document..  and I want to enter it as a key/value pair
    (err) => {
      if (err) {

Maybe is NOT possible to add a key/value pair directly on the file.

Maybe I have to add a key/value pair on the file variable… and then create a new file or overwrite the existing file…

New code… not working… I have to keep going later… any feedback would be awesome…


  const newData = (dataMain.text2 = newText); // <-- this isnt doing anything. It just prints the newText without any other information from the existing data.

  fs.appendFileSync("./thejsons/a1.json", newData, [], (err) => {  // <-- and this is only adding the newData string to a new file without any structure.. 
    if (err) {
} catch (error) {
  console.log( error);

^^ this is giving me a headache. On top of it my clearInterval() doesnt seem to be stopping my setInterval() function, which is some extra to deal with…

Some people may say I need a MongoDb data base to do CRUD operations… but this data is so small it seems so silly… on top of the extra work and resources needed for an external data base…

New code!!!

Getting closer… but only printing the last cycle of the intervals… and not getting the repeated newText by the time I create the document…

Any awesome feedbacks on how I can fix it???

console.log(newText); /// <— this is good, its changing 3 times… but at the end I am only getting the last change!!

const newData = [];

const theArray1 = `"text2": ${newData}`;
const theBrackets = `{ "res": [{${theArray1}}, ]} `;

timesRun += 1;

if (timesRun === 3) {
  fs.appendFileSync("./thejsons/a1.json", theBrackets, [], (err) => {
    if (err) {

Below is how the final newly created json file looks… format is good… but I am only getting 1 (the last)“text2” instead of 3 which is the amount of times I am running the interval…

“res”: [
“text2”: "hello back! "

***** Hint – I think this might be a problem of my Visual Studio Code… but you guys can read it all to see…

I have a JSON file to which I want to add another key/value pair kind of like this:

“text2”: “here is something else”

Here is a sample of the json:

“data”: [
“id”: “1700148573403304137”,
“text”: “hola”
“id”: “1700147255322259501”,
“text”: “hello”
“id”: “1700146984903155986”,
“text”: “hi”

Here is the code:

var data = fs.readFileSync(“./thejsons/a.json”);
var myObject = JSON.parse(data);

let toAdd = { text2: { valuefortext2 } };

var newData2 = JSON.stringify(myObject);

timesRun += 1;

if (timesRun === 3) {

  fs.writeFile("./thejsons/a1.json", newData2, (err) => {
    // error checking
    if (err) throw err;

    console.log("New data added");

Unwanted result:[textIndex++].push(toAdd); // when I add the [textIndex++] I get a typeError is not a function…

If I delete the > [textIndex++] , then I only get the last value of text2 added as an extra object in {} curly brackets at the bottom of the .data array of the json document.

ALSO… my visual studio code is re-arranging this line like this:

let newData = { text2: { valuefortext2 } };

However… I do want that data to look more like this…

let newData = “text2” : `${ valuefortext2 ’ ;

Could this be a problem with Visual Studio Code??? How can I enter the data so it will populate at the bottom of each object for the .data array???


Where is textIndex defined?

I have a feeling you are not giving us all of your code. In order to test this we will need all of it.

The code is a bit long… but I’ll put it down… most of it bringing the document, getting the data, creating an inverval function, and re-populating the json with extra new data…

> import theData from "./thejsons/a.json" assert { type: "json" };
> function newJsonData() {
>   const dataMain =;
>   const theTexts = => element.text);
>   var timesRun = 0;
>   var textIndex = 0;
>   var myIntervals = setInterval(async function (input) {
>     input = `tell me ${
>       theTexts[textIndex++]
>     }`;
>     const messages = [{ role: "user", content: input }];
>     console.log(messages);
>     const responseAI = await{
>       model: "gpt-3.5-turbo",
>       messages: messages,
>       temperature: 0,
>     });
>     const responseAItoJson = JSON.stringify(
>       responseAI.choices[0].message.content
>     );
>     // console.log(responseAItoJson);
>     var data = fs.readFileSync("./thejsons/a.json");
>     var myObject = JSON.parse(data);
>     let newData = { text2: { responseAItoJson } };
>     console.log(newData);
>     var newData2 = JSON.stringify(myObject);
>     timesRun += 1;
>     if (timesRun === 3) {
>       clearInterval(myIntervals);
>       fs.writeFile("./thejsons/a1.json", newData2, (err) => {
>         // error checking
>         if (err) throw err;
>         console.log("New data added");
>       });
>       console.log("we are done");
>     } else if (textIndex == theTexts.length) textIndex = 0;
>   }, 10 * 1000);
> }
> newJsonData();

You need to paste it in here properly so it formats correctly.

To display your code in here you need to wrap it in triple back ticks. On a line by itself type three back ticks. Then on the first line below the three back ticks paste in your code. Then below your code on a new line type three more back ticks. The back tick on my keyboard is in the upper left just above the Tab key and below the Esc key. You may also be able to use Ctrl+e to automatically give you the triple back ticks while you are typing in the this editor and the cursor is on a line by itself. Alternatively, with the cursor on a line by itself, you can use the </> button above the editor to add the triple back ticks.

I am using textIndexx to fist get something from the Json… and then using it again to put something back in the Json… maybe I can use a different tracker…

Nope… using a different tracker still gives me[textIndex2++].push(newData);

^^^ which kind of makes sense given the format ? Can I push an object into another object???

I want to push a key/value set at the bottom each object of the .data array of objects…

This here is implying that is an array of arrays. Is it?

It doesn’t look like an array of arrays.

No… would be an array of objects… and I want to add a key/value at the end of each object… but… Visual Studio code is also changing the formatting… which kind of now trying a bunch of things…

Is push defined on an object?

That is a good question…

let newData = { text2: { responseAItoJson } }; ← to begin with I don’t know what this will be…

I think somewhere in FCC there is a lesson on how to check types…

But on top visual studio code is changing the formatting, which might change the type of the item I am trying to push…

This is an object holding an array of objects.


is an object

is not valid. You cannot use .push() on an object.


Can I put a link?

geeksforgeeks .org/how-to-add-data-in-json-file-using-node-js/

^^ I am trying to follow a sample of this code… apparently they are pushing a new key/value into an object…

But yes… if I inlcude [textIndex++] the code breaksdown…
And if I don’t inlcude [textIndex++] , then it only adds the very last value as a new object at the bottom of the array…

Push is only defined on arrays. You cannot push on an object.

Note: To use push() function, data objects in json file must be stored in array. If JSON file is empty or having single object without array, push() will give error.

The article you are reading says this :point_up: They also give an example without an array. So the article is just bad.

1 Like

Yes… I just ran their code in my machine and gave me the same error…

Need to find a different wat to add a key/value pair …

Have you done an introductory JavaScript course? If not, you really should consider doing freeCodeCamp’s JavaScript curriculm

The basics can be boring, but they are very important.

Yes, I am half way through that one… the main problem with this specific code is that I want to add it repeatedly… and I didn’t know I need it to convert the json file into an object first, and then re-convert my object into a json file… and then I found a bad article.