简体   繁体   中英

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!

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) } })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM