向现有的JSON对象添加新元素

时间:2018-09-01 19:16:54

标签: javascript json node.js

我正在尝试将json对象添加到节点js中的现有文件:当成员注册时,我希望将其数据添加到我的现有json文件中。我在differents网站上找到了一些技巧和代码来实现它,但仍然没有任何效果。

我的Json文件现在看起来像这样。

{
  "Family Name": "Vincent",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "Vincent@gmail.com",
  "Event": "FE only",
  "Password" : "test"
} 

我希望他注册时看起来像这样:

{
  "Family Name": "Vincent",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "Vincent@gmail.com",
  "Event": "FE only",
  "Password" : "test"
},
{
  "Family Name": "Test",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "Okay@gmail.com",
  "Event": "FE only",
  "Password" : "test"
}

希望您能帮助我。非常感谢!

3 个答案:

答案 0 :(得分:1)

您可以使用一些现有的库(例如:lowdb

并按以下方式使用

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

答案 1 :(得分:1)

首先使用JSON数组维护数据。您可以使用节点fs模块来读取和更新文件。例如:

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": "Okay@gmail.com",
           "Event": "FE only",
           "Password" : "test"
        });
        fs.writeFileSync('user.json', JSON.stringify(userData));
    } catch (error) {
        console.log(error);
    }

}

答案 2 :(得分:0)

var json1 = {
  "Family Name": "Vincent",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "Vincent@gmail.com",
  "Event": "FE only",
  "Password" : "test"
};
var json2 = {
  "Family Name": "Test",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "Okay@gmail.com",
  "Event": "FE only",
  "Password" : "test"
  }
var arr = []; // create new empty array
arr.push(json1); // push variable1
arr.push(json2); // push variable2
console.log(arr);

结果:

[ { 'Family Name': 'Vincent',
    Name: 'Test',
    Promotion: '2A',
    Mail: 'Vincent@gmail.com',
    Event: 'FE only',
    Password: 'test' },
  { 'Family Name': 'Test',
    Name: 'Test',
    Promotion: '2A',
    Mail: 'Okay@gmail.com',
    Event: 'FE only',
    Password: 'test' } ]