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?