146

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.

codejockie
  • 9,020
  • 4
  • 40
  • 46
Romulus3799
  • 1,827
  • 3
  • 15
  • 20
  • 12
    fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output)) – Daniel Feb 11 '17 at 17:41
  • Possible duplicate of [Write objects into file with Node.js](https://stackoverflow.com/questions/21976567/write-objects-into-file-with-node-js) – Neeraj Sewani Nov 02 '18 at 12:23

5 Answers5

215

You need to stringify the object.

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output));
LightBender
  • 4,046
  • 1
  • 15
  • 31
Kamal
  • 2,550
  • 1
  • 8
  • 13
  • 2
    Welcome to SO, before answering a question, try to review the existing answer. If your answer has already been suggested, upvote that answer instead. See the [community guide](https://stackoverflow.com/help/how-to-answer) for writing a good answer. – LightBender Sep 22 '17 at 03:07
  • 55
    I like that this answers the question without opinions about whether or not to use synchronous vs async operations. – Brian Duncan Mar 30 '18 at 18:48
  • 4
    For readability purposes, you can use the space parameter of the JSON.stringify method: `fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 2));` More: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify – Binh Jan 09 '20 at 09:36
54

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

Note: If output is a string, then specify the encoding and remember the flag options as well.:

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);
codejockie
  • 9,020
  • 4
  • 40
  • 46
Akinjide
  • 2,723
  • 22
  • 28
  • 11
    If it's being done in a short script or something, synchronous is fine. If it's part of a server request or something, then it should be asynchronous. – Hilton Shumway Feb 23 '18 at 19:21
  • 1
    Not necessarily, I/O bound processes should be made asynchronous, but depending on the short script complexity you might opt in for synchronous. – Akinjide Feb 23 '18 at 21:55
  • 5
    This is not an answer to the question. – Stephan Bijzitter Mar 06 '18 at 12:52
  • 8
    User specifically asked for synchronous method – Anthony Apr 02 '18 at 22:50
  • this is generating a empty object: `{}` – fccoelho Oct 18 '18 at 12:19
  • what do you have has `output` in `const content = JSON.stringify(output);` i.e. `const content = JSON.stringify({ 'hello': 'world' });` – Akinjide Oct 18 '18 at 13:54
  • 9
    Please stop saying async good. And implying sync bad. If you are worried about speed, your webpack should do that optimization for you. You are not an optimizer. Reason: sync file writing is needed for json command-line tools. Which must close any files they have open before piping data to the next app in the chain. – TamusJRoyce Nov 01 '18 at 04:11
  • Synchronous is completely fine. There's no reason it shouldn't be accepted and supported. – Jason Rice May 05 '20 at 02:24
38

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

fs.writeFileSync('../data/phraseFreqs.json', JSON.stringify(output, null, 4));
codejockie
  • 9,020
  • 4
  • 40
  • 46
Timelot
  • 621
  • 6
  • 8
1

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(). Here is a working example:

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.

codejockie
  • 9,020
  • 4
  • 40
  • 46
1

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

const fs = require('fs');

await fs.promises.writeFile('../data/phraseFreqs.json', JSON.stringify(output)); // UTF-8 is default
Flimm
  • 136,138
  • 45
  • 251
  • 267