Properly parse CSV file to JSON file in JavaScript

638 Views Asked by At

I have a CSV file and I want to parse it using PapaParse. How do I do this properly?

I have so far:

Papa.parse(fileInput, {
    download: true,
    complete: function(results) {
        console.log(results.data);
        console.log(results.errors);
    }
});     

However, is there a better way to do this? Is this the proper way to get errors? The documentation didn't emphasize download: true or anything so I was wondering if there are any experts on this subject here.

EDIT: Also, am I suppose to further parse the file with papacsv or do it in react. For instance, if I have multiple arrays in my data file which have a similar name reference. Should I initially somehow parse the file so it groups all those references together and how would I go about doing this?

For instance,

Date, Name , Win/Lose

I want to group all the winners together. How do I do that?

2

There are 2 best solutions below

0
On

The method you are using of Papa parse, is for remote CSV.

download: true is for downloading the remote file.

By using Papa parse, this is the only way of getting errors, data, meta with parse result object.

0
On

//If(header:true)
var data = [
 {
    "date": "8/12/2018",
  "name": "foo",
  "win/loose": "win"
 },
 {
    "date": "8/12/2018",
  "name": "foo",
  "win/loose": "loose"
 },
  {
    "date": "8/12/2018",
  "name": "foo1",
  "win/loose": "win"
 },
];
var winners = data.filter(d => d['win/loose'] == 'win');
console.log(winners);
//If you want to group winners and losers then:
var grouped = data.reduce(function(acc, co) {
  var key = co['win/loose'];
  if(!acc[key]) {
    acc[key] = [];
  }
  acc[key].push(co);
  return acc;
}, {});
console.log(grouped);

This'll give you separate array of winners from extracted data.