JavaScript, Papaparse, return array of objects
Asked Answered
M

4

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

Meliamelic answered 8/1, 2020 at 18:45 Comment(1)
Papaparse is not the tool you need, it will convert into an array, not into a JSON. Search for a CSV to JSON parser.Gadmann
H
11

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.

const csvData = Papa.parse(data, { header: true });
Horologe answered 28/8, 2020 at 4:35 Comment(0)
E
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.

Easterly answered 8/1, 2020 at 18:53 Comment(1)
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 didMeliamelic
M
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.

Meliamelic answered 8/1, 2020 at 19:32 Comment(0)
K
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

Katelyn answered 8/1, 2020 at 18:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.