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

201
Views
How to append an item to a JSON stored in a file?

Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: [] Example:

[
{"name":"jhon"},
{"name":"jhonathan"}
]

Here is the code: descarga.png

Thanks.

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

0

The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.

The thing is, when you call fs.appendFile, you're only writing to the end of the file. You're not following JSON format by doing so.

You need to do this:

  1. Read file content.
  2. Parse JSON text into an object.
  3. Update the object in memory.
  4. Write object in JSON format back to the file system.

I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.

const path = __dirname + 'db.json'

// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)

// Add new item to the item list
items.push(newItem)

// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)
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!