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. 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
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!
CodePudding user response:
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' });
};
CodePudding user response:
You need to read current file, parse JSON content, modify it and then save the modified content:
const jsonString = fs.readFileSync(path);
const jsonObject = JSON.parse(jsonString);
jsonObject.push(item);
fs.writeFileSync(path, JSON.stringify(jsonObject));