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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42179037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:59:49  来源:igfitidea点击:

Writing JSON object to a JSON file with fs.writeFileSync

jsonnode.jsfilefs

提问by Romulus3799

I am trying to write a JSON object to a JSON file. The code executes without errors, but instead of the content of the object been written, all that gets written into the JSON file is:

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

[object Object]

This is the code that actually does the writing:

这是实际编写的代码:

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

'output' is a JSON object, and the file already exists. Please let me know if more information is required.

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

回答by Kamal

You need to stringify the object.

您需要对对象进行字符串化。

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

回答by akinjide

I don't think you should use the synchronous approach, asynchronously writing data to a file is better also stringify the outputif it's an object.

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

Note: If outputis a string, then specify the encoding and remember the flagoptions as well.:

注意:如果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!");
}); 

Added Synchronous method of writing data to a file, but please consider your use case. Asynchronous vs synchronous execution, what does it really mean?

添加了将数据写入文件的同步方法,但请考虑您的用例。异步与同步执行,到底是什么意思?

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

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

回答by Timelot

Make the json human readable by passing a third argument to stringify:

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

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

回答by Reza Baradaran Gazorisangi

When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify(). Hereis a working example:

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

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}`);

Hope it could help.

希望它能有所帮助。

回答by Flimm

Here's a variation, using the version of fsthat uses promises:

这是一个变体,使用fs使用 promise的版本:

const fs = require('fs');

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