javascript - How to add data to a json file? -
i have json file (it mock object works database users):
[ { "id": "0", "username": "aaaaaaaaa", "password": "xxxxxxxxx", }, { "id": "1", "username": "bbbbbbbbb", "password": "yyyyyyyyy", }, { "id": "2", "username": "ccccccccc", "password": "zzzzzzzzz", } ]
i need add new users in json file. tryed use fs.appendfile function, append user after square bracket.
how can it?
you should load json file in memory, update array , save back. like:
var users = json.parse(fs.readfilesync('yourfile.json', 'utf8')); users.push({ "id": "10", "username": "blabla", "password": "passpass", }); fs.writefilesync('yourfile.json', json.stringify(users));
Comments
Post a Comment