Home > Enterprise >  How to append an item to a JSON stored in a file?
How to append an item to a JSON stored in a file?

Time:10-22

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.

CodePudding user response:

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)
  • Related