简体   繁体   English

用 fs.append 写入 json 文件

[英]write into json file with fs.append

I am working on a project using node.js and am struggling to fit an JSON object at the right position into my already existing data.我正在使用 node.js 进行一个项目,并且正在努力将 JSON 对象在正确位置放入我现有的数据中。 My file currently looks like this:我的文件目前看起来像这样:

[
  {
    "id": "001",
    "name": "Paul,
    "city": "London"
  },
  {
    "id": "002",
    "name": "Peter,
    "city": "New York"
  },
...
]

I tried to arrange my data like:我试图安排我的数据,如:

var data = { id: id, name: name, city: city };

having the respective data stored in those variables.将相应的数据存储在这些变量中。 Then I used var json = JSON.stringify(data) and tried然后我使用var json = JSON.stringify(data)并尝试

fs.appendFile("myJSONFile.json", json, function (err) {
        if (err) throw err;
        console.log('Changed!');
    }); 

The file changes indeed but the new entry is positioned after the square bracket.文件确实发生了变化,但新条目位于方括号之后。

[
  {
    "id": "001",
    "name": "Paul,
    "city": "London"
  },
  {
    "id": "002",
    "name": "Peter,
    "city": "New York"
  },
...
]{"id":"004","name":"Mark","city":"Berlin"}

How do I get it alongside the previous entries?我如何将它与以前的条目放在一起? Any help would be truly appreciated!任何帮助将不胜感激!

You need to first read the file, in your case you are storing an array in the file.您需要先读取文件,在您的情况下,您要在文件中存储一个数组。 So, you need to push your object to the array that you read from the file, and write the result back to the file (not append):因此,您需要将对象推送到从文件中读取的数组,并将结果写回文件(不追加):

const fs = require('fs/promises');

// ...

const addToFile = async data => {
  let fileContents = await fs.readFile('myJSONFile.json', { encoding: 'utf8' });
  fileContents = JSON.parse(fileContents);
  const data = { id, name, city };
  fileContents.push(data);
  await fs.writeFile('myJSONFile.json', JSON.stringify(fileContents, null, 2), { encoding: 'utf8' });
};

You need to read current file, parse JSON content, modify it and then save the modified content:您需要读取当前文件,解析 JSON 内容,对其进行修改,然后保存修改后的内容:

const jsonString = fs.readFileSync(path);
const jsonObject = JSON.parse(jsonString);
jsonObject.push(item);
fs.writeFileSync(path, JSON.stringify(jsonObject));

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

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