javascript 反应:导入 csv 文件并解析

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/53416529/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 10:11:09  来源:igfitidea点击:

React: import csv file and parse

javascriptreactjscsvparsingimport

提问by BluePrint

I have the following csv file that is named data.csvand located in the same folder as my js controller:

我有以下 csv 文件,data.csv该文件与我的 js 控制器位于同一个文件夹中:

namn,vecka,m?ndag,tisdag,onsdag,torsdag,fredag,l?rdag,s?ndag
Row01,a,a1,a2,a3,a4,a5,a6,a7
Row02,b,b1,b2,b3,b4,b5,b6,b7
Row03,c,c1,c2,c3,c4,c5,c6,c7
Row04,d,d1,d2,d3,d4,d5,d6,d7
Row05,e,e1,e2,e3,e4,e5,e6,e7
Row06,f,f1,f2,f3,f4,f5,f6,f7
Row07,g,g1,g2,g3,g4,g5,g6,g7
Row08,h,h1,h2,h3,h4,h5,h6,h7
Row09,i,i1,i2,i3,i4,i5,i6,i7
Row10,j,j1,j2,j3,j4,j5,j6,j7
Row11,k,k1,k2,k3,k4,k5,k6,k7
Row12,l,l1,l2,l3,l4,l5,l6,l7

In react, I need to import a csv file and parse it to JSON. I tried the following:

在反应中,我需要导入一个 csv 文件并将其解析为 JSON。我尝试了以下方法:

componentWillMount() {
    this.getCsvData();
}

getData(result) {
    console.log(result);
}

getCsvData() {
    let csvData = require('./data.csv');

    Papa.parse(csvData, {
        complete: this.getData
    });
}

This doesnt work for some reason. The first console.log displays /static/media/data.0232d748.csvand the second displays the following:

由于某种原因,这不起作用。第一个 console.log 显示/static/media/data.0232d748.csv,第二个显示以下内容:

{
  "data": [
    [
      "/static/media/horoscope-data.0232d748.csv"
    ]
  ],
  "errors": [
    {
      "type": "Delimiter",
      "code": "UndetectableDelimiter",
      "message": "Unable to auto-detect delimiting character; defaulted to ','"
    }
  ],
  "meta": {
    "delimiter": ",",
    "linebreak": "\n",
    "aborted": false,
    "truncated": false,
    "cursor": 41
  }
}

I don't understand what I am doing wrong. Can someone help me?

我不明白我做错了什么。有人能帮我吗?

回答by BluePrint

To answer my own question, I was able to rewrite it like this (/src/controllers/data-controller/data-controller.js, added the full code for better clarity):

为了回答我自己的问题,我能够像这样重写它(/src/controllers/data-controller/data-controller.js为了更清晰,添加了完整代码):

import React from 'react';
import Papa from 'papaparse';
import {withRouter} from 'react-router-dom';

class DataController extends React.Component {

    constructor(props) {
        super(props);

        this.state = {
            data: []
        };

        this.getData = this.getData.bind(this);
    }

    componentWillMount() {
        this.getCsvData();
    }

    fetchCsv() {
        return fetch('/data/data.csv').then(function (response) {
            let reader = response.body.getReader();
            let decoder = new TextDecoder('utf-8');

            return reader.read().then(function (result) {
                return decoder.decode(result.value);
            });
        });
    }

    getData(result) {
        this.setState({data: result.data});
    }

    async getCsvData() {
        let csvData = await this.fetchCsv();

        Papa.parse(csvData, {
            complete: this.getData
        });
    }

    render() {
        return (
            <section className="data-controller">
                ...
            </section>
        );
    }
}

export default withRouter(DataController);

Here I use the built in fetch to get it like a stream and then read the stream using the build in stream reader, and decode the data using TextDecoder. I had to move the file also. Before it was located in /src/controllers/data-controllerbut I had to move it to /public/data.

在这里,我使用内置的 fetch 将其像流一样获取,然后使用内置的流读取器读取流,并使用TextDecoder. 我也不得不移动文件。在它位于之前,/src/controllers/data-controller但我不得不将它移动到/public/data.

回答by Brian Burns

Here's a similar example using React Hooks -

这是一个使用 React Hooks 的类似示例 -

import React from 'react'
import Papa from 'papaparse'

export default function() {
  const [rows, setRows] = React.useState([])
  React.useEffect(() => {
    async function getData() {
      const response = await fetch('/data/nodes.csv')
      const reader = response.body.getReader()
      const result = await reader.read() // raw array
      const decoder = new TextDecoder('utf-8')
      const csv = decoder.decode(result.value) // the csv text
      const results = Papa.parse(csv, { header: true }) // object with { data, errors, meta }
      const rows = results.data // array of objects
      setRows(rows)
    }
    getData()
  }, []) // [] means just do this once, after initial render
  return (
    <div className="app">
      <Table cols={tripColumns} rows={rows} />
    </div>
  )
}