Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
So I am trying to store JSON data in a variable in a Vue project.
The code to upload and store the file is
<input type="file" id="file" ref="fileSelect" class="custom-file-input" @change="showfiles" />
<script lang="ts">
methods: {
showfiles() {
let files = this.$refs.fileSelect.files //Error Object is of type 'unknown'. ts(2571)
var reader = new FileReader();
reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
reader.readAsText(files[0]);
console.log(this.p) //I am storing JSON data in p
I searched online and found various fixes but none of them are working for me
I tried adding "useUnknownInCatchVariables": false
to tsconfig, it fixes the error momentarily but the error comes back.
I also tried try and catch
showfiles() {
let files = this.$refs.fileSelect.files
var reader = new FileReader();
reader.onload = ({ target: { result }}) => { this.p = JSON.parse(result); };
reader.readAsText(files[0]);
console.log(this.p)
catch(err) {
if (err instanceof Error) {
console.log(err.message);
} else {
console.log('Unexpected error', err);
But none of these worked.
I'll greatly appreciate any suggestion.
Try to cast the type of fileSelect
ref yourself like that:
showfiles() {
const files = (this.$refs.fileSelect as HTMLInputElement).files // const files: FileList | null
// ...
I guess you are not reading the result correctly. According to MDN you should just take the result from filereader's result
property.
reader.addEventListener("load", () => {
this.p = JSON.parse(reader.result);
}, false);
–
–
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.