简体   繁体   中英

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?

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>
  );
}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM