1

I am writing JSON objects to a file that are streaming from the twitter api. They log to the console correctly and look like JSON objects; however, when I use the command:

fs.appendFile("./tweets.json", tweet) 

All that writes to the file is the following:

[object Object] 

What is going on here? When I write the object tweet to console, this is the output:

 { created_at: 'Tue Mar 17 22:12:41 +0000 2015', id: 577955743997018100, id_str: '577955743997018112', text: ......tons more stuff.... filter_level: 'low', lang: 'en', timestamp_ms: '1426639434951' } 

What is [object Object] and why is it writing that?

1
  • 2
    If you see [object Object] in your file then tweet is not a string containing data in the JSON format, but a regular javascript object. And the console output : { created_at: 'Tue Mar 17 22:12:41 +0000 2015', shows clearly that it is not JSON. In a JSON formatted string the key needs to be quoted with double-quotes. Commented Mar 18, 2015 at 2:17

2 Answers 2

7

Change this line

fs.appendFile("./tweets.json", tweet); 

to

fs.appendFile("./tweets.json", JSON.stringify(tweet, null, ' ')); 

This is because appendFile will call toString() which will print what you see, so you need to turn the object into a JSON string.

The second two arguments to stringify will pretty print the JSON object so that you can look at it and edit it manually. If you prefer the compact format, simply leave those out.

Sign up to request clarification or add additional context in comments.

Comments

1

The fs.appendFile expects a string. But you give it an object. All you need to do is to convert the object to string. Call the JSON.stringify.

fs.appendFile("./tweets.json", JSON.stringify(tweet)) 

If fs.appendFile does not receive a string then it tries to convert the argument to string. And does it badly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.