Search code examples
node.jsjsonfs

unable to add json content to an existing json file using Node.js


I have a json prepared file with key-value pairs as arrays. I am writing a program to add new static json (in the same format) to the existing file using "fs" module. I am aware that we cannot just straight-up append json data to json file. Hence, I converted both file and to-be added data to string using JSON.stringify() first. Post this, I tried to use fs.write / fs.appendFile to get the data inserted using JSON.parse() but I end up getting error! Also, I tried to use .push() mehtod but it throws err - "undefined"

let fs = require('fs');
let news = { 
    "person4": [
        {
            "first": "Karan",
            "last": "Mahajan"
        }
    ],
    "person5" : [
        {
            "first": "Sahil",
            "last": "Mahajan"
        }
    ]
};


fs.readFile(__dirname + "/" + "repository.json" , "utf-8", (err,data) => {
    let x = JSON.stringify(data);
    let y = JSON.stringify(news);
    let z = x+y;
    fs.appendFile(__dirname + "repository.json" , JSON.parse(z) , "utf-8", (err) => {
        console.log("error is " + err);
    });
    
});

File: repository.json

{   
   "person1": [
    {
      "first": "Nicole",
      "last": "Adelstein"
    }],   
   "person2": [
    {
      "first": "Pleuni",
      "last": "Pennings"
    }],
    "person3": [
    {
      "first": "Rori",
      "last": "Rohlfs"
    }] 
}

Solution

  • You're getting an error because you're using the JSON.parse/stringify in a wrong way. When you read a file with fs.readFile you receive a string with the whole content. So, what you need to do is to use a JSON.parse on what you received, manipulate the object and then write back to file the result.

    You can also change the way you rewrite the file, because when you use appendFile becomes hard to deal with the data and manipulate the json object. To do so, I recommend use writeFile. How could be:

    index.js

    let fs = require("fs");
    const i = require("./repository.json");
    let news = {
      person4: [
        {
          first: "Karan",
          last: "Mahajan",
        },
      ],
      person5: [
        {
          first: "Sahil",
          last: "Mahajan",
        },
      ],
    };
    
    fs.readFile(__dirname + "/" + "repository.json", "utf-8", (err, data) => {
      let x = JSON.parse(data);
      let y = news;
      fs.writeFile(
        __dirname + "/" + "repository.json",
        JSON.stringify({ ...x, ...y }, 0, 2),
        "utf-8",
        (err) => {
          console.log("error is " + err);
        }
      );
    });
    

    repository.json

    {
      "person1": [
        {
          "first": "Nicole",
          "last": "Adelstein"
        }
      ],
      "person2": [
        {
          "first": "Pleuni",
          "last": "Pennings"
        }
      ],
      "person3": [
        {
          "first": "Rori",
          "last": "Rohlfs"
        }
      ]
    }
    

    Result in repository.json

    {
      "person1": [
        {
          "first": "Nicole",
          "last": "Adelstein"
        }
      ],
      "person2": [
        {
          "first": "Pleuni",
          "last": "Pennings"
        }
      ],
      "person3": [
        {
          "first": "Rori",
          "last": "Rohlfs"
        }
      ],
      "person4": [
        {
          "first": "Karan",
          "last": "Mahajan"
        }
      ],
      "person5": [
        {
          "first": "Sahil",
          "last": "Mahajan"
        }
      ]
    }