1

I need to select a .csv file in html and manage it with javascript (I need to convert it into JSON), I did something but it doesn't work well.

To select a file in html I did this:

<input id="inputFile" accept=".csv" type="file"> <br>

<br>
<input value="Send" type="button" onclick="showFile()"> 
<label id="mylabel">
</label>

<script src="../javascript/parseFileScript.js"></script>

and to manage it I did this:

//take a string containing a csv
function csvJSON(csv){
    console.log(typeof csv)
    var lines=csv.split("\n");

    var result = [];

    // NOTE: If your columns contain commas in their values, you'll need
    // to deal with those before doing the next step
    // (you might convert them to &&& or something, then covert them back later)
    // jsfiddle showing the issue https://jsfiddle.net/
    var headers=lines[0].split(",");

    for(var i=1;i<lines.length;i++){

        var obj = {};
        var currentline=lines[i].split(",");

        for(var j=0;j<headers.length;j++){
            obj[headers[j]] = currentline[j];
        }

        result.push(obj);

    }

    //return result; //JavaScript object
    return JSON.stringify(result); //JSON
}

//load the selected file and convert in string
async function getCSV() {
    let file = document.getElementById('inputFile').files[0];
    console.log(typeof file)
    let text = await file.text();
    return text;
}

//put the body of the selected file in a label
function showFile() {
    let csv = getCSV();
    let json = csvJSON(csv);
    document.getElementById('mylabel').innerHTML = json;
}

The error I get is Uncaught TypeError: csv.split is not a function, so I check for the type of csv in the function csvJSON and for the type of file in getCSV and in both cases the console tells me that the type is object.

Can someone explain to me where I'm wrong and how to solve the problem, please?

3
  • split is a function of the String prototype. As your wrote yourself, your input is not a string. Commented Aug 10, 2020 at 11:12
  • @Lain thanks, but maybe help me to solve the problem too ^^ Commented Aug 10, 2020 at 11:16
  • 2
    Change console.log(typeof csv) to console.log(csv) and you shall find the right property. Also your source has an interesting comment leading to here. Commented Aug 10, 2020 at 11:26

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.