Tag Archives: NodeJS

How to Write JSON Object to File in Node.js

How To Write JSON Object to File 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.");
});

 

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.

 

In the above program, you might have observed that bothjsonData andjsonContent 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.