Vincent Tng
Vincent Tng

Reputation: 145

Adding a New Element to an existing JSON Object

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 !

Upvotes: 3

Views: 7794

Answers (2)

amrender singh
amrender singh

Reputation: 8239

First 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);
    }

}

Upvotes: 2

hovnozrout
hovnozrout

Reputation: 121

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()

Upvotes: 1

Related Questions