将新元素添加到现有JSON对象

问题描述 投票:1回答:3

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

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

{
  "Family Name": "Vincent",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "[email protected]",
  "Event": "FE only",
  "Password" : "test"
} 

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

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

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

javascript json node.js
3个回答
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
投票

首先使用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": "[email protected]",
           "Event": "FE only",
           "Password" : "test"
        });
        fs.writeFileSync('user.json', JSON.stringify(userData));
    } catch (error) {
        console.log(error);
    }

}

0
投票
var json1 = {
  "Family Name": "Vincent",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "[email protected]",
  "Event": "FE only",
  "Password" : "test"
};
var json2 = {
  "Family Name": "Test",
  "Name": "Test",
  "Promotion": "2A",
  "Mail": "[email protected]",
  "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: '[email protected]',
    Event: 'FE only',
    Password: 'test' },
  { 'Family Name': 'Test',
    Name: 'Test',
    Promotion: '2A',
    Mail: '[email protected]',
    Event: 'FE only',
    Password: 'test' } ]
© www.soinside.com 2019 - 2024. All rights reserved.