write to a json file in javascript

To write to a JSON file in JavaScript using Node.js, you can use the fs module which is built into Node.js. Here's an example code snippet:

index.tsx
const fs = require('fs');

// Create a JavaScript object
const myObj = { name: "John", age: 31, city: "New York" };

// Convert the object to a JSON string
const jsonString = JSON.stringify(myObj);

// Write the JSON string to a file
fs.writeFile('myFile.json', jsonString, err => {
  if (err) {
    console.log('Error writing file', err);
  } else {
    console.log('Successfully wrote file');
  }
});
403 chars
17 lines

In this example, we start by requiring the fs module. We then create a JavaScript object called myObj. We convert this object to a JSON string using JSON.stringify(). Finally, we use fs.writeFile() to write the JSON string to a file called myFile.json.

Note: If the file myFile.json doesn't exist, fs.writeFile() will create it. If it already exists, fs.writeFile() will overwrite it with the new JSON data.

gistlibby LogSnag