最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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"
]

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"
]
Share Improve this question edited Sep 9, 2020 at 15:49 Abraham asked Jul 29, 2018 at 6:31 AbrahamAbraham 9,8756 gold badges55 silver badges58 bronze badges 1
  • You may find stackoverflow.com/questions/2496710/… useful, using JSON.stringify to turn the JSON object into a string (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…). – msbit Commented Jul 29, 2018 at 6:34
Add a comment  | 

1 Answer 1

Reset to default 16

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!");
}); 
发布评论

评论列表(0)

  1. 暂无评论