0

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"
    }] 
}

1 Answer 1

1

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"
    }
  ]
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thanks, @Bernardo! I tried running with the above modification but the file still remains unchanged. Moreover, the console prints error is null :(
@KNIGHTMAHAJAN Could you give more informations? I tried the same code and get the expected result.
please refer to this sandbox link - codesandbox.io/s/elegant-scott-3h68r0?file=/index.js
Thanks, @BERNARDO! The code works and new data is getting added. Could you please illustrate the purpose of JSON.stringify({ ...x, ...y }, 0, 2) ?
Sure! The { ...x, ...y } is called Spread Syntax basically I am using it to create a new object with the content of the another two and then stringify to become an string and be inserted on the file. The options that I added ( 0, 2 ) only do the outcome prettier and readable, you can see more here
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.