i'm trying to add a json object to an existing file in node js: When a members sign up, I want his data to be added to my existing json file. I've found on differents website some tips and code to make it happen but still, it doesnt have any effects.
My Json file look like this right now.
{
"Family Name": "Vincent",
"Name": "Test",
"Promotion": "2A",
"Mail": "[email protected]",
"Event": "FE only",
"Password" : "test"
}
And I want him to look like this when he register :
{
"Family Name": "Vincent",
"Name": "Test",
"Promotion": "2A",
"Mail": "[email protected]",
"Event": "FE only",
"Password" : "test"
},
{
"Family Name": "Test",
"Name": "Test",
"Promotion": "2A",
"Mail": "[email protected]",
"Event": "FE only",
"Password" : "test"
}
Hope you can help me. Thanks a lot !
i'm trying to add a json object to an existing file in node js: When a members sign up, I want his data to be added to my existing json file. I've found on differents website some tips and code to make it happen but still, it doesnt have any effects.
My Json file look like this right now.
{
"Family Name": "Vincent",
"Name": "Test",
"Promotion": "2A",
"Mail": "[email protected]",
"Event": "FE only",
"Password" : "test"
}
And I want him to look like this when he register :
{
"Family Name": "Vincent",
"Name": "Test",
"Promotion": "2A",
"Mail": "[email protected]",
"Event": "FE only",
"Password" : "test"
},
{
"Family Name": "Test",
"Name": "Test",
"Promotion": "2A",
"Mail": "[email protected]",
"Event": "FE only",
"Password" : "test"
}
Hope you can help me. Thanks a lot !
Share Improve this question edited Sep 1, 2018 at 19:41 amrender singh 8,2494 gold badges26 silver badges30 bronze badges asked Sep 1, 2018 at 19:16 Vincent TngVincent Tng 1454 silver badges12 bronze badges 1-
You need an JSON array at first place. surround the content of the json file with
[ ]
, thenvar a = JSON.parse
, thena.push(newvalue)
thenJSON.stringify(a)
then save the content in the file. Otherwise you won't end up with a valid json file. – mpm Commented Sep 1, 2018 at 19:19
2 Answers
Reset to default 2First of all use a JSON array to maintain your data. You can use the node fs
module for reading and updating your file. For Example:
const fs = require('fs');
function readFileAndSaveData(){
try {
let userData = fs.readFileSync('user.json');
userData = JSON.parse(userData);
userData.push({
"Family Name": "Test",
"Name": "Test",
"Promotion": "2A",
"Mail": "[email protected]",
"Event": "FE only",
"Password" : "test"
});
fs.writeFileSync('user.json', JSON.stringify(userData));
} catch (error) {
console.log(error);
}
}
You can use some existing libraries (ex: lowdb)
and use it as below
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
const adapter = new FileSync('yourfile.json')
const db = low(adapter)
db
.get('users')
.push({ "Family Name": "Vincent", "Name": "Test", ... })
.write()
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745075342a4609800.html
评论列表(0条)