Javascript 使用Node.js将对象添加到JSON

Javascript 使用Node.js将对象添加到JSON,javascript,json,node.js,Javascript,Json,Node.js,我有一个JSON文件,需要用作添加、删除和修改用户的数据库,我有以下代码: 'use strict'; const fs = require('fs'); let student = { id: 15, nombre: 'TestNombre', apellido: 'TestApellido', email: 'TestEmail@gmail.com', confirmado: true }; let data = JSON.string

我有一个JSON文件,需要用作添加、删除和修改用户的数据库,我有以下代码:

'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);
但这会覆盖JSON文件,我需要作为另一个对象进行追加,因此它将继续使用ID15(最后一个是14)

以下是JSON文件的一部分:

{
  "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
    },
  ]
}

如何执行此操作?

每次要写入JSON文件时,都需要先读取/解析它,更新对象,然后将其写入磁盘

已经有一个流行的解决方案来处理这个问题。结帐

对于自动索引,我相信文档为本模块提供了一些帮助程序库来实现这一点


不要重新发明轮子

每次要写入JSON文件时,都需要先读取/解析它,更新对象,然后将其写入磁盘

已经有一个流行的解决方案来处理这个问题。结帐

对于自动索引,我相信文档为本模块提供了一些帮助程序库来实现这一点


不要重新发明轮子

只需
require
文件,在
personas
道具中推送
student
,然后
writeFileSync

'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));

只需
require
文件,在
personas
道具中推送
student
,然后
writeFileSync

'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));

首先加载文件,将其保存在内存中,每次更新该对象时,也会将其存储回文件中。有一些很好的node_模块可以为您执行fs操作,并使您看起来像是在处理数据。我想到的是,这是复制品吗?首先加载文件,将其保存在内存中,每次更新该对象时,也会将其存储回文件中。有一些很好的node_模块可以为您执行fs操作,并使您看起来像是在处理数据。我想到的是,这是复制品吗?为什么要同步?只是好奇地匹配OP的首选方法。他/她已经使用了
fs。writeFileSync
在问题代码片段中。啊!好吧,我想也许真的有必要:谢谢!这正是我要找的!为什么要同步?只是好奇地匹配OP的首选方法。他/她已经使用了
fs。writeFileSync
在问题代码片段中。啊!好吧,我想也许真的有必要:谢谢!这正是我要找的!