how do i push data to an array in a json file and save it?

When you import the contents of testlist.json into the variable testlist using require(), you are loading the file’s contents into memory. You will need to write back to the file after you have made changes to the testlist variable if you want your modifications to persist. Otherwise, the changes that you make will be lost when the program’s process exits.

You can use the writeFileSync() method from the fs module, as well as JSON.stringify(), to write testlist back into the testlist.json file:

const fs = require("fs");

let testlist = require("../testlist.json");

// Your code where you modify testlist goes here

// Convert testlist to a JSON string
const testlistJson = JSON.stringify(testlist);
// Write testlist back to the file
fs.writeFileSync("../testlist.json", testlistJson, "utf8");

Edit: You should also use the readFileSync() method (also from the fs module), and JSON.parse() to perform the initial reading of the JSON file, rather than require().

// This line
let testlist = require("../testlist.json");

// Gets replaced with this line
let testlist = JSON.parse(fs.readFileSync("../testlist.json", "utf8"));

You have to use JSON.parse as well as fs.readFileSync because when you are reading the file, it is read as a string, rather than a JSON object.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top