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

3
  • Does this answer your question? Convert CSV data into JSON format using Javascript Commented May 11, 2020 at 6: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 Commented May 11, 2020 at 6: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 Commented May 11, 2020 at 6:34

2 Answers 2

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
}

Sign up to request clarification or add additional context in comments.

1 Comment

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
2

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.