Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

103
Views
escribir en el archivo json con fs.append

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!

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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' }); };
about 4 years ago · Juan Pablo Isaza Report

0

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));
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!