Im want to display the keys of the object of a json file imported in the v-file-input tag, and i tried to use FileReader for it but it also gives me the same error:
Uncaught TypeError: Failed to execute 'readAsText' on 'FileReader': parameter 1 is not of type 'Blob'.
This Is my code:
<template>
<v-file-input accept=".json" v-model="selectedFile" label="Application's Data File"></v-file-input>
<v-btn class="my-3 ml-10" v-if="validated" @click="validate">Validate</v-btn>
</template>
<script setup>
const selectedFile = ref();
const validated = ref(true);
const validate = () => {
const file = selectedFile instanceof FileList ? selectedFile[0] : selectedFile;
if (file) {
const reader = new FileReader();
reader.onload = (e) => {
console.log(e.target.result);
const content = e.target.result;
try {
const jsonObject = JSON.parse(content);
console.log(jsonObject); // This is the parsed JSON object
} catch (error) {
console.log("Invalid JSON file:", error);
}
};
reader.readAsText(selectedFile);
}
};
</script>
There are several issues:
selectedFile
is a ref, so selectedFile instanceof FileList
will always be falsemodelValue
uses File[]
, so checking against FileList will not workreader.readAsText(selectedFile)
reads the ref, but you want to read file
So this gives you:
const validate = () => {
const fileList = selectedFile.value // <--- unwrap ref
const file = Array.isArray(fileList) ? fileList[0] : fileList // <---- check if array (shouldn't be necessary)
if (file) {
const reader = new FileReader()
reader.onload = e => {
console.log(e.target.result)
const content = e.target.result
try {
const jsonObject = JSON.parse(content)
console.log(jsonObject) // This is the parsed JSON object
} catch (error) {
console.log('Invalid JSON file:', error)
}
}
reader.readAsText(file) // <---- pass in extracted file
}
}
Here it is in a playground