首页 > 解决方案 > 如何将字符串数组保存到 Javascript 中的 JSON 文件?

问题描述

如何将字符串数组保存到Node.jsJSON中的文件中:

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

例子.json

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

标签: javascriptarraysjsonnode.js

解决方案


在 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!");
}); 

推荐阅读