so i try to convert CSV file from input tag to JSon using this template and code below:
<input type="file" ref="myfile" @change="csvJSON($event)" />
csvJSON(csv) {
console.log(csv)
var lines = csv.split('\n')
var result = []
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)
}
console.log('data', result)
},
but it keeps showing this error as i already target the event value on it, can someone tell me where did i do wrong here?
TypeError: csv.split is not a function
at VueComponent.csvJSON (Tables.vue?074c:179:1)
at change (Tables.vue?8f4b:282:1)
at invokeWithErrorHandling (vue.runtime.esm.js?2b0e:3015:1)
at HTMLInputElement.invoker (vue.runtime.esm.js?2b0e:1813:1)
at original_1._wrapper (vue.runtime.esm.js?2b0e:7458:1)
CodePudding user response:
You need to await the file content to be loaded using the event target files :
async csvJSON(event) {
const file = event.target.files.item(0)
const csv = await file.text();
console.log(csv)
var lines = csv.split('\n')
var result = []
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)
}
console.log('data', result)
},