Convert JSON to CSV

Asked

Viewed 195 times

0

I’m developing a tool that captures information from the github API and saves it to a file .json.

Code:

const axios = require('axios')

const fs = require('fs')

const data = require('./data.json');

async function getResult(data) {

    for(a = 0; a < data.length; a++){

        data[a].atividades = {};

        for(b = 1; b <= 3; b++) {

            let lista = `Lista_${b}`;

            var res = await axios.get(`https://api.github.com/repos/org/repo/contents/turma-1/${data[a].REPO}/${lista}`)

            data[a].atividades[lista] = res.data.length - 1
        }
    }
    
    return data
}

getResult(data).then((res) => {
    console.log('casa', res);

    var array = []
    array.push(res)
    
    
    var arrayResultado = array
    var ArraySerealizado = JSON.stringify(arrayResultado)
    var caminhoDoArquivo = './resultado.json'
    fs.writeFileSync(caminhoDoArquivo, ArraySerealizado)
})
.catch(err => {
    console.log(err)
})

Running generates this json output:

{
      "ID": 199,
      "NOME": "Davi xxxxx",
      "REPO": "xxxxx",
      "atividades": {
        "Lista_1": 0,
        "Lista_2": 0,
        "Lista_3": 0
      }
    },

I needed to convert this 'result.json' to a CSV file where the structure looked like this;

column 1: name column 2: Reference column 3: list_1 column 4: list_2

And so on and so forth...

Would it be necessary to change something in my code or is there a way to turn json into csv the way I have it now?

Thank you!

1 answer

1

Speak David, all right? Dude, try to follow up with your json:

var csv = json.map(function(row){
  return fields.map(function(fieldName){
    return JSON.stringify(row[fieldName], replacer)
  }).join(',')
})

csv.unshift(fields.join(','))
csv = csv.join('\r\n');
console.log(csv)
  • Hi John, thank you for the answer! Can you explain this resolution a little better? I’m entering the world of Javascript now and confess that I don’t understand exactly how to do :(

Browser other questions tagged

You are not signed in. Login or sign up in order to post.