Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

120
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda