简体   繁体   中英

json2csv and fs module for nested objects

I'm trying to format my json file to csv file so I can use it in Google Sheets. So far I had succeed it. But my object of personalInfo is in one cell in Google Sheets and not seperate in two cells.

Here is the json file, which is an array of objects:

  [{
            "email": "abc@gmail.com",
            "phone": "000 000 000",
            "personalInfo": 
                 {
                 "firstName": "John",
                 "lastName": "doe"
                 }
    }
]

Here is my code:

const fs = require("fs");
const { Parser } = require('json2csv');

const fields = ['email', 'phone', 'personalInfo'];
const opts = { fields };
    
const parser = new Parser(opts);
const csv = parser.parse(new_arr);
    
fs.writeFile('file.csv', csv, function(err) {
    if (err) throw err;
    console.log('file saved');
});

I tried to add 'firstName' and 'lastName' in my const fields but it only add the title name to column and the object 'personalInfo' is still in one cell (which is not one cell for 'firstName' and 'lastName')

You need to specify the path properly.

ie

const fs = require("fs");
const { Parser } = require('json2csv');

const fields = ['email', 'phone', 'personalInfo.firstName', 'personalInfo.lastName'];
const opts = { fields };
    
const parser = new Parser(opts);
const csv = parser.parse(new_arr);
    
fs.writeFile('file.csv', csv, function(err) {
    if (err) throw err;
    console.log('file saved');
});

From the docs you can also use flatten :

// Default
flatten();

// Custom separator '__'
flatten({ separator: '_' });

// Flatten only arrays
flatten({ objects: false, arrays: true });

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