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
fs
is the Node.js file system module, it can not use in browsers environment. Consider use browser compatible library like PapaParse.
@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
}