w3resource

JavaScript: Write a JSON object to a file

JavaScript fundamental (ES6 Syntax): Exercise-251 with Solution

Write JSON to File

Write a JavaScript program to write a JSON object to a file.

  • Use fs.writeFileSync(), template literals and JSON.stringify() to write a json object to a .json file.

Sample Solution:

JavaScript Code:

//#Source https://bit.ly/2neWfJ2 
// Import the 'fs' module to work with the file system
const fs = require('fs');

// Define a function 'JSONToFile' that writes a JSON object to a file
const JSONToFile = (obj, filename) =>
  // Write the JSON object to a file with the provided filename and '.json' extension
  fs.writeFile(`${filename}.json`, JSON.stringify(obj, null, 2));

// Call 'JSONToFile' with a sample JSON object and filename
JSONToFile({ test: 'is passed' }, 'testJsonFile'); // writes the object to 'testJsonFile.json'

Flowchart:

flowchart: Write a JSON object to a file.

For more Practice: Solve these Related Problems:

  • Write a JavaScript program in Node.js that writes a JSON object to a file using the fs module.
  • Write a JavaScript function that serializes an object to JSON and saves it asynchronously to disk.
  • Write a Node.js program that converts an object to a JSON string and writes it to a file with proper error handling.
  • Write a JavaScript program that uses fs.writeFileSync to write JSON data to a file and then reads it back for verification.

Go to:


PREV : Create Element from String.
NEXT : RGB to Color Code.

Improve this sample solution and post your code through Disqus

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.