4

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 ?

4 Answers4

12

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>
  );
}
junkie
  • 358
  • 2
  • 7
3

I have not used any external library to parse the CSV file.

Refer to the code below:

App.js File

import React, { useState } from "react";
   
  export default function App() {
     const [file, setFile] = useState();
   
     const fileReader = new FileReader();
   
     const handleOnChange = (e) => {
      // console.log(e.target);
       setFile(e.target.files[0]);
      // console.log(e.target.files[0]);


     };
   
     const csvFileToArray = string => {
       var array = string.toString().split(" ")
      //  console.log(array); here we are getting the first rows which is our header rows to convert it into keys we are logging it here
        var data = []
        // console.log(data);
        for(const r of array){
          // console.log(r);
            let row = r.toString().split(",")
            data.push(row)
        }
        console.log(data)
        var heading = data[0]
        // console.log(heading); to get the column headers which will act as key
        var ans_array = []
        // console.log(ans_array);
        for(var i=1;i<data.length;i++){
            var row = data[i]
            var obj = {}
            for(var j=0;j<heading.length;j++){
                if(!row[j]){
                    row[j]="NA";
                }
                // console.log(row[j].toString())
                obj[heading[j].replaceAll(" ","_")] = row[j].toString().replaceAll(" ","_")
            }
            ans_array.push(obj)
        }
        console.log({ans_array})
     };
   
     const handleOnSubmit = (e) => {
       e.preventDefault();
   
       if (file) {
         fileReader.onload = function (event) {
           const text = event.target.result;
          //  console.log(event);
          //  console.log(event.target.result);
           csvFileToArray(text);
         };
   
         fileReader.readAsText(file);
       }
     };
   
     return (
       <div style={{ textAlign: "center" }}>
         <h1 style={{color:"red"}}>CSV PARSER</h1>
         <br></br>
         <form>
           <input
             type={"file"}
             id={"csvFileInput"}
             accept={".csv"}
             onChange={handleOnChange}
           />
   
           <button
             onClick={(e) => {
               handleOnSubmit(e);
             }}
           >
             IMPORT CSV
           </button>
         </form>
   
         <br />
       </div>
     );
   }

see the output of csv to json conversion in console.

1

You can use Papaparse, it can be used for the below requirements,

CSVReader – React component that handles CSV file input and returns its content as an array.

CSVDownloader – React component that renders the link/button which is clicked to download the data provided in CSV format.

readString – The function that reads CSV comma-separated string and returns its content as an array.

readRemoteFile – The function that read remote CSV files and returns their content as an array.

jsonToCSV – The function that reads an array of the object (JSON) and returns its content as a CSV comma-separated string.

In the code, I have used it to read remote CSV files and converted them into JSON,

import React from 'react';

import React from 'react';

import { usePapaParse } from 'react-papaparse'; import xlsx from 'xlsx';

export default function App() { const { readRemoteFile } = usePapaParse(); const link = 'link of csv';

const handleReadRemoteFile = () => {
    readRemoteFile(link, {
        header: true,
        complete: (results) => {
            const JsonObject = JSON.stringify(results);
            console.log(JsonObject);
        },
    });
};

return < button onClick = {
    () => handleReadRemoteFile()
} > readRemoteFile < /button>;

}

You can refer to the link below.

https://github.com/Raja-shekaran/React-papaparse-CSVTOJSON.git

0

You can refer this link below.

https://www.npmjs.com/package/react-papaparse

On handleOnFileLoad method, you will receive data fetched from csv file. You will have a JSON response directly from there. The above link does not support xlxs format. You need to have another npm package for it.