Node.js Write JSON Object to File
We can save a JSON object to an external file in filesystem. This ability may help to save results, intermediate results or sometimes debug our program.
Node.js Write JSON Object to File – In this tutorial, we shall learn how to write a JSON Object to a local file.
To write a JSON Object to a local file, following is a step-by-step guide :
- Stringify JSON Object.
Use JSON.stringify(jsonObject) to convert JSON Object to JSON String. - Write the stringified object to file using fs.writeFile() function of Node FS module.
Example 1 – Write JSON Object to File in Node.js
In the following Nodejs 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.
We would like to save this JSON object to a file.
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.
nodejs-write-json-object-to-file.js
// file system module to perform file operations
const fs = require('fs');
// json data
var jsonData = '{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}';
// parse json
var jsonObj = JSON.parse(jsonData);
console.log(jsonObj);
// stringify JSON Object
var jsonContent = JSON.stringify(jsonObj);
console.log(jsonContent);
fs.writeFile("output.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.");
});
Useful Link – To access elements of JSON Object, refer Node.js Parse JSON.
Run the above program in Terminal with node command
$ node nodejs-write-json-object-to-file.js
{ persons:
[ { name: 'John', city: 'New York' },
{ name: 'Phil', city: 'Ohio' } ] }
{"persons":[{"name":"John","city":"New York"},{"name":"Phil","city":"Ohio"}]}
JSON file has been saved.
A Big Note
In the above program, you might have observed that both jsonData and jsonContent when logged to console result in same output. This is because when the JSON Object is logged to console, toString method is called implicitly. But if you attempt to write the JSON object to a file directly without prior Stringify, it results in [Object Object] written to file.
Concluding this Node.js Tutorial – Node.js Write JSON Object to File, we have learned to write a JSON Object to a file using JSON.stringify() function and FS.writeFile() function.