Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

121
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda