26-Sep-2022
.
Admin
Hello Friends,
Today, I will give you an example of how to write json object to a file in nodejs. we will help you to give an example of write json object to a file in node js. We will look at an example of write json object to a file in node.js. if you want to see an example of nodejs write json object to file, then you are in the right place.
In this example write json object to file in nodejs. I will script, we have JSON data stored as string in variable jsonData. We then used JSON.parse() function to JSONify the string. So now we have a JSON object. Until now we simulated the situation where you have obtained or created a JSON object.
To save the JSON object to a file, we stringify the json object jsonObj and write it to a file using Node FS’s writeFile() function.
So, let's start following example:
Step 1: Install Node JS
This step is not required; however, if you have not created the node js app, then you may go ahead and execute the below command:
mkdir my-app
cd my-app
npm init
Step 2: Update server.js file
server.js
const fs = require('fs');
// json data
var jsonData = '{"persons":[{"name":"Piyush","city":"Rajkot"},{"name":"Vivek","city":"Surat"}]}';
// parse json
var jsonObj = JSON.parse(jsonData);
console.log(jsonObj);
// stringify JSON Object
var jsonContent = JSON.stringify(jsonObj);
console.log(jsonContent);
fs.writeFile("demo.json", jsonContent, 'utf8', function (err) {
if (err) {
console.log("An error occured while writing JSON Object to File.");
return console.log(err);
}
console.log("JSON file has been saved.");
});
Output:
{
persons: [
{ name: 'Piyush', city: 'Rajkot' },
{ name: 'Vivek', city: 'Surat' }
]
}
{"persons":[{"name":"Piyush","city":"Rajkot"},{"name":"Vivek","city":"Surat"}]}
JSON file has been saved.
I hope it can help you...
#Node JS