Estoy trabajando en un proyecto usando node.js y estoy luchando para colocar un objeto JSON en la posición correcta en mis datos ya existentes. Mi archivo actualmente se ve así:
[ { "id": "001", "name": "Paul, "city": "London" }, { "id": "002", "name": "Peter, "city": "New York" }, ... ]Traté de organizar mis datos como:
var data = { id: id, name: name, city: city }; teniendo los respectivos datos almacenados en dichas variables. Luego usé var json = JSON.stringify(data) y probé
fs.appendFile("myJSONFile.json", json, function (err) { if (err) throw err; console.log('Changed!'); });De hecho, el archivo cambia, pero la nueva entrada se coloca después del corchete.
[ { "id": "001", "name": "Paul, "city": "London" }, { "id": "002", "name": "Peter, "city": "New York" }, ... ]{"id":"004","name":"Mark","city":"Berlin"}¿Cómo lo obtengo junto con las entradas anteriores? ¡Cualquier ayuda sería realmente apreciada!
Primero debe leer el archivo, en su caso, está almacenando una matriz en el archivo. Por lo tanto, debe enviar su objeto a la matriz que leyó del archivo y escribir el resultado nuevamente en el archivo (no agregarlo):
const fs = require('fs/promises'); // ... const addToFile = async data => { let fileContents = await fs.readFile('myJSONFile.json', { encoding: 'utf8' }); fileContents = JSON.parse(fileContents); fileContents.push(data); await fs.writeFile('myJSONFile.json', JSON.stringify(fileContents, null, 2), { encoding: 'utf8' }); };Debe leer el archivo actual, analizar el contenido JSON, modificarlo y luego guardar el contenido modificado:
const jsonString = fs.readFileSync(path); const jsonObject = JSON.parse(jsonString); jsonObject.push(item); fs.writeFileSync(path, JSON.stringify(jsonObject));