Joey
Joey

Reputation: 203

Writing JSON data to a file incorrectly

I'm reading information from a api which returns text in JSON format. I want to take that text and write it to a file. When I do it writes it with a \ in front of everything looks like this .

[{ \"ElementA":\"ValueA" ... }]

Here's what I've tried

var info = []
request('someApi', function(err, res, body) {
  if (err) {
    return console.log('Error:', err);
  }
  if (res.statusCode != 200) {
    return console.log('Invalid:' + res.statusCode);
  }
  info = JSON.stringify(body);
  fs.writeFile('public/file', info);
});

Also the file that I'm trying to write to is .JS if that makes any difference. My desired output is :

 [{ "ElementA": "Value A ...}]

Upvotes: 2

Views: 208

Answers (1)

thefourtheye
thefourtheye

Reputation: 239653

As the data which you are trying to write is already a well formed JSON, you don't have to JSON.stringify it and you can simply write it as it is, like this

fs.writeFile('public/file', body, callbackFunction);

Note: fs.writeFile is an async function. You need to pass the callback function as well, which will be invoked when the actual writing is completed.

Upvotes: 4

Related Questions