English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Node.js writes a JSON object to a file– In this article, we will learn how to write a JSON object to a local file.
To write a JSON object to a local file, please follow the following step-by-step guide:
Stringify the JSON object. UseJSON.stringify(jsonObject) converts the JSON object to a JSON string.
Use fs to write the stringified object to the file. The writeFile() function of the Node FS module.
In the following Nodejs script, the JSON data is stored as a string in the variable jsonData. Then we use the JSON.parse() function to JSONify the string. Now we have a JSON object. So far, we have simulated that you have already obtained or created a JSON object.
We want to save this JSON object to a file.
To save the JSON object to a file, we will stringify the JSON object, and then use the Node FS writeFile() function to write it to the file.
// The file system module performs 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 occurred while writing JSON Object to File."); return console.log(err); } console.log("JSON file has been saved."); });
Run the above program using the node command in the Terminal
Node.js Script Terminal Output
$ 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 may have noticed that both hjsondata and jsoncontent produce the same output when logged into the console. This is because when a JSON object is logged to the console, the toString method is implicitly called. However, if you try to write a JSON object to a file without first stringifying it, it will result in [object object] to the file.
Conclusion Node.js Tutorial-We have learned to write JSON objects to files using the JSON.stringify() function and the FS.writeFile file() function in node.js.