簡體   English   中英

Append 一個新的 object 到 JSON 文件中的一個數組

[英]Append a new object to an array in a JSON file

如何將額外的 object 添加到作為對象數組的現有 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");
}

這給出了 output:

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

}

但是我需要:

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

    }
]

如何使其正確寫入數組?

將 JSON 形式的預序列化元素附加到預先存在的 JSON 文件中具有直觀意義。 您可能會嘗試切掉文件中的尾部"]" ,用前置逗號寫入新元素,然后重新附加"]"

但這可能在很多方面都錯了。 The better approach is to read the file, parse the JSON into a JS object, make the desired modification(s) to the object, serialize the object back to JSON and finally write the string back to the file.

此代碼顯示了所有這些步驟以及生成示例數據的初始寫入:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM