How to read data From *.CSV file using javascript?

后端 未结 13 809
不知归路
不知归路 2020-11-22 00:46

My csv data looks like this:

heading1,heading2,heading3,heading4,heading5,value1_1,value2_1,value3_1,value4_1,value5_1,value1_2,value2_2,value3_2,val

13条回答
  •  無奈伤痛
    2020-11-22 01:24

    A bit late but I hope it helps someone.

    Some time ago even I faced a problem where the string data contained \n in between and while reading the file it used to read as different lines.

    Eg.

    "Harry\nPotter","21","Gryffindor"
    

    While-Reading:

    Harry
    Potter,21,Gryffindor
    

    I had used a library csvtojson in my angular project to solve this problem.

    You can read the CSV file as a string using the following code and then pass that string to the csvtojson library and it will give you a list of JSON.

    Sample Code:

    const csv = require('csvtojson');
    if (files && files.length > 0) {
        const file: File = files.item(0);
        const reader: FileReader = new FileReader();
        reader.readAsText(file);
        reader.onload = (e) => {
        const csvs: string = reader.result as string;
        csv({
            output: "json",
            noheader: false
        }).fromString(csvs)
            .preFileLine((fileLine, idx) => {
            //Convert csv header row to lowercase before parse csv file to json
            if (idx === 0) { return fileLine.toLowerCase() }
            return fileLine;
            })
            .then((result) => {
            // list of json in result
            });
        }
    }
    

提交回复
热议问题