2

I am trying to convert a .csv file into a JSON object in Reactjs. For this, I add the file I need to convert into the project structure under a folder called Data. I then found this npm package https://www.npmjs.com/package/convert-csv-to-json and tried the following piece of code to convert file

import { getJsonFromCsv } from "convert-csv-to-json";
...
let json = getJsonFromCsv('./Data/finaldata.csv');
for (let i = 0; i < json.length; i++) {
console.log(json[i]);
}

But trying this is throwing an

"TypeError: fs.readFileSync is not a function"

So I would like to know if something is wrong with my code or Can someone suggest another method to convert CSV file to JSON

Hisoka
  • 101
  • 3
  • 15
  • Does this answer your question? [Convert CSV data into JSON format using Javascript](https://stackoverflow.com/questions/27979002/convert-csv-data-into-json-format-using-javascript) – Daniel Brose May 11 '20 at 06:15
  • I tried one of the answers in that using papa-parse but it seems react-papa-parse only works if I upload a file and then read it. But I don't want to upload I just want to read from a file that is already in project structure – Hisoka May 11 '20 at 06:29
  • Many solutions work if we upload the file and then parse it. but I am looking for one where we need not upload file we read it from local storage and parse it – Hisoka May 11 '20 at 06:34

2 Answers2

3

@kartik try it

//var csv is the CSV file with headers
function csvJSON(csv){

  var lines=csv.split("\n");

  var result = [];

  var headers=lines[0].split(",");

  for(var i=1;i<lines.length;i++){

   var obj = {};
   var currentline=lines[i].split(",");

   for(var j=0;j<headers.length;j++){
    obj[headers[j]] = currentline[j];
   }

   result.push(obj);

  }
  
  //return result; //JavaScript object
  return JSON.stringify(result); //JSON
}
Makwana Prahlad
  • 1,025
  • 5
  • 20
  • 1
    i understood the function but how to pass my required file as param to that function. Could you answer that by assuming the required file is in local storage – Hisoka May 12 '20 at 09:54
2

fs is the Node.js file system module, it can not use in browsers environment. Consider use browser compatible library like PapaParse.

L_K
  • 2,838
  • 2
  • 16
  • 36