简体   繁体   中英

How to add to existing data in a JSON file using javascript?

I used writeFile() function, but the new data overwrites the existing data. How can I fix this code? Here's what I have right now :

var obj = {username:user_name, password:password}; 
  jsonfile.writeFile(file, obj, function (err) {  
      console.error(err);
}); 

Using Node.js (v0.5.x +), you can load JSON files with the require function; this automatically parses the file as an object. You can then add or modify keys and values as you would any other object, before stringifying it and overwriting the old file with the original and newly appended or modified data:

const fs = require("fs");

var jsonObject = require("filename.json");

jsonObject.test = 99;
jsonObject.password = "ABCDEFG";

fs.writeFile("filename.json", JSON.stringify(jsonObject), "utf8", function(err) {
    if (err) throw err;
    console.log("File saved.");
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM