Skip to content
Advertisement

How to convert csv file data to json object in reactjs?

I want to get csv file from input tag and convert data of csv file into json object. Is there any plugin in react js or any custom code ?

Advertisement

Answer

You can use an external library like Papa Parse to parse the CSV data.

A simple input tag with type as file would work to read the CSV data.

      <input
        type="file"
        accept=".csv,.xlsx,.xls"
        onChange={handleFileUpload}
      />

Please declare handleFileUpload function and use the library inside to parse the read data.

Here’s an example which will read a CSV file and log the corresponding JSON:

import Papa from "papaparse";

export default function App() {
  return (
    <div className="App">
      <input
        type="file"
        accept=".csv,.xlsx,.xls"
        onChange={(e) => {
          const files = e.target.files;
          console.log(files);
          if (files) {
            console.log(files[0]);
            Papa.parse(files[0], {
              complete: function(results) {
                console.log("Finished:", results.data);
              }}
            )
          }
        }}
      />
    </div>
  );
}
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement