5

I'm using to Papaparse to convert a csv file to json object.

The API expects the data in this way:

"data": [
        {
            "id": 1,
            "nombre": "AGUASBLANCAS-AGB",
            "descripcion": "-",
            "it_unidad_generadora": 0
        },
        {
            "id": 425,
            "nombre": "AGUASBLANCAS-AGBQ",
            "descripcion": "-",
            "it_unidad_generadora": 403
        }
    ]

But with Papaparse, the csv is converted to an array of arrays of each row like this:

"data":  [
    0: ["ID", "NOMBRE", "DESCRIPCIÓN", "IT UNIDAD GENERADORA"]
    1: ["1", "AGUASBLANCAS-AGB", "-", "0"]
    2: ["425", "AGUASBLANCAS-AGBQ", "-", "403"]
    ]

Is there a way to make an JSON array of object with Papaparse? and not an array of arrays of each rows

pmiranda
  • 7,602
  • 14
  • 72
  • 155

4 Answers4

8

According to the docs here: https://www.papaparse.com/docs#config

You simply need to set header: true on the options, for the result to become an array of objects.

Matt Way
  • 32,319
  • 10
  • 79
  • 85
1

Instead of Papaparse, you can use this library https://www.npmjs.com/package/csvtojson

It has a good number of downloads and can help you with the data you are expecting it to be.

Shubham Nagota
  • 187
  • 1
  • 11
  • Thanks mate, I tried just before Papaparse, but it doesn't work on browser, I can't read files there. With Papaparser was very easy, I will post an answer of what finally I did – pmiranda Jan 08 '20 at 19:24
1

I did it like this way:

Papa.parse(event.target.files[0], {complete: async results => {
    let keys = results.data[0];
    // I want to remove some óíúáé, blan spaces, etc
    keys = results.data[0].map(v => v.toLowerCase().replace(/ /g,"_").normalize('NFD').replace(/[\u0300-\u036f]/g,""));

    let values = results.data.slice(1);
    let objects = values.map(array => {
      let object = {};
      keys.forEach((key, i) => object[key] = array[i]);
      return object;
    });
    // Now I call to my API and everything goes ok
    await uploadCSV(type, objects);
  }
});

Nothing to do with Papaparse config, but I had to use js to create objects with the desires keys from the first row of the array of arrays.

pmiranda
  • 7,602
  • 14
  • 72
  • 155
0

I don't use paparse often however I think this document here helps you out https://github.com/PolymerVis/papa-parse/blob/master/README.md

Alisina Saemi
  • 65
  • 1
  • 9