jprichardson / node-jsonfile

Easily read/write JSON files.
MIT License
1.2k stars 321 forks source link

jsonfile append #78

Closed nomanmaqsood closed 7 years ago

nomanmaqsood commented 7 years ago

I am trying to append the json file but it is creating file like this

{"id":1, name: "abc"}
{"id":2, name: "cde"}
{"id":3, name: "fgh"}

so in reading json file it is creating error.

Is there anyway to create file like this ?

{[
{"id":1, name: "abc"},
{"id":2, name: "cde"},
{"id":3, name: "fgh"}
]}
RyanZim commented 7 years ago

You simply need a file like this to be able to read it:

[
  {"id":1, name: "abc"},
  {"id":2, name: "cde"},
  {"id":3, name: "fgh"}
]

To get a file like that, you would need to do something like this:

const file = 'path/to/file.json'
jsonfile.readFile(file, (err, data) => {
  if (err) console.log(err)
  data.push({ id: 4, name: 'ijk' })
  jsonfile.writeFile(file, data, err => {
    if (err) console.log(err)
  })
})

Hope that helps!