Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

119
Views
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')

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You need to specify the path properly.

i.e.

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 });
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!