简体   繁体   English

如何将 csv 文件数据转换为 Z3C797270102480CB4D1207D1E1D07A3 中的 json object?

[英]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.我想从输入标签中获取 csv 文件并将 csv 文件的数据转换为 json ZA8CFDE6331BD59EB2AC96F8911B4。 Is there any plugin in react js or any custom code? react js中是否有任何插件或任何自定义代码?

You can use an external library like Papa Parse to parse the CSV data.您可以使用像Papa Parse这样的外部库来解析 CSV 数据。

A simple input tag with type as file would work to read the CSV data.类型为文件的简单输入标签可以读取 CSV 数据。

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

Please declare handleFileUpload function and use the library inside to parse the read data.请声明handleFileUpload function 并使用里面的库来解析读取的数据。

Here's an example which will read a CSV file and log the corresponding JSON:这是一个示例,它将读取 CSV 文件并记录相应的 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 https://www.npmjs.com/package/react-papaparse

On handleOnFileLoad method, you will receive data fetched from csv file.在 handleOnFileLoad 方法中,您将收到从 csv 文件中获取的数据。 You will have a JSON response directly from there.您将直接从那里收到 JSON 响应。 The above link does not support xlxs format.以上链接不支持 xlxs 格式。 You need to have another npm package for it.你需要另一个 npm package 。

I have not used any external library to parse the CSV file.我没有使用任何外部库来解析 CSV 文件。

Refer to the code below:参考下面的代码:

App.js File应用程序.js 文件

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.在控制台中查看 output 的 csv 到 json 转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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