I want to save my JavaScript object to a JSON file. I already did like this
const superagent = require('superagent');
const cheerio = require('cheerio');
const fs = require('fs');
var object = new Object();
var toJson = { articles: [] };
var arr = [];
// I obtain the data prior to this forEach loop.
// The data loading code is omitted, because it is too long to fit here.
data.forEach((val, index) => {
const authorName = val.authorName;
const articleDate = val.articleDate;
const relateArticle = val.relateArticle;
const relateArticleURL = val.relateArticleURL;
object.url = arr[1][index];
object.title = arr[0][index];
object.date = articleDate[0];
object.author = authorName[0];
toJson.articles.push(object);
});
var saveJson = JSON.stringify(toJson)
fs.writeFile('solution.json', saveJson, 'utf8', (err) => {
if (err) {
console.log(err)
}
})
I would expect the result to look like so:
{
"articles": [
{
"url": "...",
"title": "...",
"author": "...",
"postingDate: "..."
}
]
}
but what I get instead looks like so:
{"articles":[{"url":"...","title":"...","author":"...","postingDate":"..."}]}
How do I save an object to a JSON file, but in the desired format? Any answer would be appreciated. Thank you in advance!
JSON.stringify- oh, you want it pretty ... JSON.stringify takes 3 arguments - check out the documentation)JSON.stringifyfunction that you need to use.