如何在JavaScript中将字符串数组保存到JSON文件?

8
我该如何在Node.js中将字符串数组保存到JSON文件中?
const alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'];

example.json

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

你可能会发现 https://dev59.com/vXE95IYBdhLWcg3wApLl 很有用,使用 JSON.stringify 将 JSON 对象转换为字符串 (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify)。 - msbit
1个回答

15
在Node.js中,您可以这样做。
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!");
}); 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接