简体   繁体   中英

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: 'TestEmail@gmail.com',
    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": "aureliaosborn@lovepad.com",
      "confirmado": false
    },
    {
      "id": 1,
      "nombre": "Curry",
      "apellido": "Jefferson",
      "email": "curryjefferson@lovepad.com",
      "confirmado": true
    },
  ]
}

How can I do this?

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!

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: 'TestEmail@gmail.com',
    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));

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