0

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)
1
  • It's telling you the argument being passed is not a string. Look at the Vue documentation for @change Commented Nov 7, 2022 at 6:49

1 Answer 1

2

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)
        },
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.