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

问题描述 投票:-2回答:1

我如何保存字符串在Node.js的一个.json文件的数组:

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

example.json

[
  "a", "b", "c", "d", "e", "f", "g", "h"
]
javascript arrays json node.js
1个回答
2
投票

在节点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!");
}); 
© www.soinside.com 2019 - 2024. All rights reserved.