【问题标题】:Append a new object to an array in a JSON file将新对象附加到 JSON 文件中的数组
【发布时间】:2021-06-23 08:08:08
【问题描述】:

如何向作为对象数组的现有 JSON 文件添加其他对象?

这是我的 JS 代码:

const fs = require("fs");

let Human = { 
    Name: "John",
    age: 20,

};

Human = JSON.stringify(Human, null, 2)

fs.appendFile('users.json', Human, error);

function error(err) {
    console.log("1");
}

这给出了输出:

[
    {
      "Name": "John",
      "age": 20,
    },
    
    {
      "Name": "John",
      "age": 20,
    }
]{
  "Name": "John",
  "age": 20,

}

但我需要:

[
    {
      "Name": "John",
      "age": 20,
    },
    
    {
      "Name": "John",
      "age": 20,
    },
    {
      "Name": "John",
      "age": 20,

    }
]

如何让它正确写入数组?

【问题讨论】:

  • 欢迎来到 SO!请不要试图用垃圾邮件绕过质量过滤器——它的存在是有原因的。将您的 JSON 文件解析为 JS 数组,使用 Array#push 作为新条目,然后将对象重新字符串化为 JSON 并转储回文件。
  • @ggorlen TypeError: 无法读取未定义的属性“推送”
  • @ggorlen 我需要在 [] 中添加什么?

标签: javascript node.js arrays json


【解决方案1】:

将 JSON 形式的预序列化元素附加到预先存在的 JSON 文件中具有直观意义。您可以尝试在文件中切掉尾部"]",用前置逗号写入新元素,然后重新附加"]"

但这可能会在很多方面出错。更好的方法是读取文件,将 JSON 解析为 JS 对象,对对象进行所需的修改,将对象序列化回 JSON,最后将字符串写回文件。

此代码显示了所有这些步骤以及生成示例数据的初始写入:

const fs = require("fs").promises;

(async () => {
  // generate a sample JSON file
  const filename = "users.json";
  let users = [
    {
      name: "Amy",
      age: 21,
    },
    {
      name: "Bob",
      age: 23,
    },
  ];
  await fs.writeFile(filename, JSON.stringify(users));

  // append a new user to the JSON file
  const user = {
    name: "John",
    age: 20,
  };
  const file = await fs.readFile(filename);
  users = JSON.parse(file);
  users.push(user);
  await fs.writeFile(filename, JSON.stringify(users, null, 4));
})();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-21
    • 2013-08-20
    • 1970-01-01
    • 2015-09-11
    • 2020-12-03
    相关资源
    最近更新 更多