使用 fs.writeFileSync 将 JSON 对象写入 JSON 文件

Writing JSON object to a JSON file with fs.writeFileSync

我正在尝试将 JSON 对象写入 JSON 文件。代码执行没有错误,但是写入 JSON 文件的不是对象的内容,而是:

[object Object]

这是实际写入的代码:

fs.writeFileSync('../data/phraseFreqs.json', output)

'output' 是一个 JSON 对象,文件已经存在。如果需要更多信息,请告诉我。

我认为您不应该使用同步方法,将数据异步写入文件最好也将 output 字符串化(如果它是 object)。

注意:如果 output 是字符串,则指定编码并记住 flag 选项。:

const fs = require('fs');
const content = JSON.stringify(output);

fs.writeFile('/tmp/phraseFreqs.json', content, 'utf8', function (err) {
    if (err) {
        return console.log(err);
    }

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

添加了将数据写入文件的同步方法,但请考虑您的用例。 Asynchronous vs synchronous execution, what does it really mean?

const fs = require('fs');
const content = JSON.stringify(output);

fs.writeFileSync('/tmp/phraseFreqs.json', content);

您需要将对象字符串化。

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));

通过将第三个参数传递给 stringify 使 json 人类可读:

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 4));

向网络服务器发送数据时,数据必须是字符串 (here)。您可以使用 JSON.stringify() 将 JavaScript 对象转换为字符串。 Here 是一个工作示例:

var fs = require('fs');

var originalNote = {
  title: 'Meeting',
  description: 'Meeting John Doe at 10:30 am'
};

var originalNoteString = JSON.stringify(originalNote);

fs.writeFileSync('notes.json', originalNoteString);

var noteString = fs.readFileSync('notes.json');

var note = JSON.parse(noteString);

console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);

希望对您有所帮助。

这里有一个变体,使用使用承诺的 fs 版本:

const fs = require('fs');

await fs.promises.writeFile('../data/phraseFreqs.json', JSON.stringify(output)); // UTF-8 is default