November
11th,
2016
First, we need to have a JSON file with empty array or existing array with objects. Suppose this users.json
:
For append new content to users.json
file we need to read the file and convert it contents to an JavaScript object using JSON.parse()
method:
Now arrayOfObjects
variable contains a object from users.json
file:
Now we can write the data into an users
array using the push()
method is as follows:
Now we have an array with an object:
You can appended any objects to users
array.
After we have data in variable we need to write this into file:
You may have noticed that here uses JSON.stringify(arrayOfObjects)
. JSON.stringify()
method convert the contents of arrayOfObjects
into JSON.
Now users.json
looks like this:
Full Code:
index.js
users.json