简体   繁体   English

如何在 Node Js 中写入文件时将 object 推入数组中

[英]How to push object inside an array while writing to a file in Node Js

How to push object inside an array while writing to a file in Node Js?如何在 Node Js 中写入文件时将 object 推入数组中? I currently have the following working code我目前有以下工作代码

fs.appendFile("sample.json", JSON.stringify(data, undefined, 2) + ",");

where data is an object, like其中数据是 object,例如

{
name:'abc',
age: 22,
city: 'LA'
}

Upon appending, which results the following附加后,结果如下

{
name:'abc',
age: 22,
city: 'LA'
},
{
name:'def',
age: 25,
city: 'MI'
},

I see 2 problems here.我在这里看到两个问题。 1. The trailing comma at the end 2. The inability to form an array and push the object into it 1.末尾的逗号 2.无法形成数组并将object推入其中

Any leads would be appreciated任何线索将不胜感激

Append will append your data to a file and here data is being treated as a string and all appends will be equal to concating string to another string. Append 将 append 您的数据到一个文件,这里的数据被视为一个字符串,所有附加将等于将字符串连接到另一个字符串。

Instead, here the file needs to be read first and converted to a data-structure for this example it can be an array of objects and convert that data-structure to string and write it to file.相反,这里需要首先读取文件并将其转换为该示例的数据结构,它可以是对象数组,然后将该数据结构转换为字符串并将其写入文件。

To write to the file写入文件

fs.writeFileSync('sample.json', JSON.stringify([data], null, 2));

sample.json样品.json

[
  {
    "name": "abc",
    "age": 22,
    "city": "LA"
  }
]

Read from file从文件中读取

const fileData = JSON.parse(fs.readFileSync('sample.json'))
fileData.push(newData)

Write the new data appended to previous into file将附加到先前的新数据写入文件

fs.writeFileSync('sample.json', JSON.stringify(fileData, null, 2));

sample.json样品.json

[
  {
    "name": "abc",
    "age": 22,
    "city": "LA"
  },
  {
    "name": "abc",
    "age": 22,
    "city": "LA"
  }
]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM