Writing JSON object to a JSON file with fs.writeFileSync

Romulus3799 picture Romulus3799 · Feb 11, 2017 · Viewed 142k times · Source

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:

[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.

Answer

Kamal picture Kamal · Sep 22, 2017

You need to stringify the object.

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