Abraham
Abraham

Reputation: 9865

How to save an array of strings to a JSON file in Javascript?

How can I save an array of strings to a JSON file in Node.js:

const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

example.json

[
  "a",
  "b",
  "c",
  "d",
  "e", 
  "f",
  "g",
  "h"
]

Upvotes: 9

Views: 21013

Answers (1)

Anshul Bansal
Anshul Bansal

Reputation: 1893

In Node js you can do like this.

const fs = require('fs');
var alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const jsonContent = JSON.stringify(alphabet);

fs.writeFile("./alphabet.json", jsonContent, 'utf8', function (err) {
    if (err) {
        return console.log(err);
    }

    console.log("The file was saved!");
}); 

Upvotes: 16

Related Questions