Nachot93
Nachot93

Reputation: 63

Add object to JSON with Node.js

I have a JSON file that I need to use as a database to add, remove and modify users, I have this code:

'use strict';

const fs = require('fs');

let student = {  
    id: 15,
    nombre: 'TestNombre', 
    apellido: 'TestApellido',
    email: '[email protected]',
    confirmado: true 
};


let data = JSON.stringify(student, null, 2);
fs.writeFileSync('personas.json', data);

But that overwrites the JSON file, and I need to append as another object, so it continues with id 15 (last one was 14).

Here is a piece of the JSON file:

{
  "personas": [
    {
      "id": 0,
      "nombre": "Aurelia",
      "apellido": "Osborn",
      "email": "[email protected]",
      "confirmado": false
    },
    {
      "id": 1,
      "nombre": "Curry",
      "apellido": "Jefferson",
      "email": "[email protected]",
      "confirmado": true
    },
  ]
}

How can I do this?

Upvotes: 0

Views: 2196

Answers (2)

nicholaswmin
nicholaswmin

Reputation: 22989

Just require the file, push the student in the personas prop and writeFileSync it back.

'use strict';

const fs = require('fs');

let current = require('./personas.json');
let student = {
    id: 15,
    nombre: 'TestNombre',
    apellido: 'TestApellido',
    email: '[email protected]',
    confirmado: true
};

current.personas.push(student);

// Make sure you stringify it using 4 spaces of identation
// so it stays human-readable.
fs.writeFileSync('personas.json', JSON.stringify(current, null, 4));

Upvotes: 2

Antiokus
Antiokus

Reputation: 544

every time you want to write to the JSON file, you’ll need to read it first/parse it, update he Object and then write it to disk.

There’s a popular solution already handling that. Checkout lowdb

For the autoindexing - I believe the documentation suggests ways some helper libraries for this module to make that happen

Don’t reinvent the wheel!

Upvotes: 1

Related Questions