Farhan Rabbaanii
Farhan Rabbaanii

Reputation: 463

how to save js object to JSON format

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!

Upvotes: 2

Views: 2742

Answers (1)

Ronald M. Kasendwa
Ronald M. Kasendwa

Reputation: 458

Try this

const superagent = require('superagent');
const cheerio = require('cheerio');
const fs = require('fs');

var object = new Object();
var toJson = { articles:[] }; 
var arr = [];

// above this for each, is how i get the data. i don't put those code because it's too long.
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, null, 4)

        fs.writeFile('solution.json', saveJson, 'utf8', (err)=>{
            if(err){
                console.log(err)
            }
        })

Upvotes: 1

Related Questions