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?

fabianod
  • 501
  • 4
  • 17
  • [split](https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/String/split) is a function of the `String` prototype. As your wrote yourself, your input is not a string. – Lain Aug 10 '20 at 11:12
  • @Lain thanks, but maybe help me to solve the problem too ^^ – fabianod Aug 10 '20 at 11:16
  • 2
    Change `console.log(typeof csv)` to `console.log(csv)` and you shall find the right property. Also your [source](https://stackoverflow.com/a/27979069/4728913) has an interesting comment leading to [here](https://stackoverflow.com/a/59219146/4728913). – Lain Aug 10 '20 at 11:26

0 Answers0