How to add data to a JSON file in JavaScript
JavaScript Object Notation (JSON) is a lightweight format for exchanging data. It is not only easy for humans to read and write in JSON, but it can be efficiently parsed and generated by machines. JSON is often used for exchanging data between web servers and web applications because it can be easily transmitted over the internet and can be parsed by many programming languages.
Let’s discuss the steps for adding data to a JSON file in JavaScript.
Steps
Suppose we want to add data in the following JSON file.
{"users": [{"name": "John Doe","email": "john.doe@example.com"},{"name": "Jane Smith","email": "jane.smith@example.com"},{"name": "Bob Johnson","email": "bob.johnson@example.com"}]}
We have to go through the following steps for adding the data in the data.json file using JavaScript:
We first need to read the file’s contents using the
readFileSync()method as given below.
const data = fs.readFileSync('data.json');
Parse the JSON data into a JavaScript object using the
JSON.parse()method as follows:
const jsonData = JSON.parse(data);
Modify the
jsonDataobject as follows:
jsonData.users.push({name: 'James',email: 'james@example.com',// or any other data we want to add in that object});
Write the updated JavaScript object back to the JSON file using the
writeFileSync()method as follows:
fs.writeFileSync('data.json', JSON.stringify(jsonData));
Let's run the following widget and update the record of the data.json file by adding some data to it.
{
"users": [
{
"name": "John Doe",
"email": "john.doe@example.com"
},
{
"name": "Jane Smith",
"email": "jane.smith@example.com"
},
{
"name": "Bob Johnson",
"email": "bob.johnson@example.com"
}
]
}
Explanation
Line 1: Import the
fsmodule for reading and writing into the file.Line 4: Read data from the file using the
readFileSync()method.Lines 11–14: Modify the JavaScript object by adding new data.
Line 18: Convert the JavaScript object back into a JSON string.
Lines 20–23: Write updated data into the file,
data.json, using thewriteFileSync()method.Lines 25–27: Prints the content of the updated
data.jsonfile.
The next question that comes to mind is whether we can add different patterns compared to the existing pattern of the data. The answer is yes. To test it out, you can run the following executable to get an idea of how it works fine.
{
"users": [
{
"name": "John Doe",
"email": "john.doe@example.com"
},
{
"name": "Jane Smith",
"email": "jane.smith@example.com"
},
{
"name": "Bob Johnson",
"email": "bob.johnson@example.com"
}
]
}
Free Resources