From 6bc8897e1e9173173f8d4763989d65c298e87f3a Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 21 Feb 2023 12:14:09 -0600 Subject: [PATCH] Add Write A JavaScript Object To A JSON File as a JavaScript TIL --- README.md | 3 +- ...rite-a-javascript-object-to-a-json-file.md | 46 +++++++++++++++++++ 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 javascript/write-a-javascript-object-to-a-json-file.md diff --git a/README.md b/README.md index 123cb75..e07d18c 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://crafty-builder-6996.ck.page/e169c61186). -_1284 TILs and counting..._ +_1285 TILs and counting..._ --- @@ -479,6 +479,7 @@ _1284 TILs and counting..._ - [Turn Off Console Error Messages In A Test](javascript/turn-off-console-error-messages-in-a-test.md) - [Waiting On Multiple Promises](javascript/waiting-on-multiple-promises.md) - [Who Am I: NPM Edition](javascript/who-am-i-npm-edition.md) +- [Write A JavaScript Object To A JSON File](javascript/write-a-javascript-object-to-a-json-file.md) - [Yarn Commands Without The Emojis](javascript/yarn-commands-without-the-emojis.md) - [Yup Schemas Are Validated Asynchronously](javascript/yup-schemas-are-validated-asynchronously.md) diff --git a/javascript/write-a-javascript-object-to-a-json-file.md b/javascript/write-a-javascript-object-to-a-json-file.md new file mode 100644 index 0000000..2031177 --- /dev/null +++ b/javascript/write-a-javascript-object-to-a-json-file.md @@ -0,0 +1,46 @@ +# Write A JavaScript Object To A JSON File + +To write a JavaScript object to a file as JSON, I need to use two concepts. + +First, I need to use +[`JSON.stringify`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) +to conver the object to a string of valid JSON. Plus, by specifying the third +argument as `2`, I get an indentation of two spaces as it formats the JSON. + +```javascript +JSON.stringify(data, null, 2) +``` + +Second, I need to import the `fs` (filesystem) package so that I can write the +JSON string to a file. In this example, I've chosen to use the synchronous +version +([`writeFileSync`](https://nodejs.org/api/fs.html#fswritefilesyncfile-data-options)) +to keep my function simple. There is also an async version. + +```javascript +import fs from 'fs' + +fs.writeFileSync('my-data.json', json_string, 'utf8') +``` + +Here is a full example of what this could look like: + +```javascript +import fs from 'fs' + +const writeJsonToFile = (path, data) => { + try { + fs.writeFileSync(path, JSON.stringify(data, null, 2), 'utf8') + console.log('Data successfully saved to disk') + } catch (error) { + console.log('An error has occurred ', error) + } +} + +const data = { + name: 'Super Software LLC', + orgIds: [1,3,7,11] +} + +writeJsonToFile('my-data.json', data) +```