how to read the content of a json by VUE

Asked

Viewed 692 times

2

I need to receive a file json for input type file and read the contents of this file on the front without having to make a request to the server.

<input type="file" id="file" ref="file" v-on:change="handleFileUpload()" />

handleFileUpload() {
  var reader = new FileReader();
  var file = this.$refs.file.files[0];
  reader.onload = function() {
   console.log(reader.result)
  };
  reader.readAsText(file)
},

I can print the file in the console but not put it in a variable to use inside the code.

1 answer

1

So I did some tests here and I did it this way:

methods: {
    parse(){
      var reader = new FileReader();
      reader.onload = this.onReaderLoad;
      reader.readAsText(this.$refs.myFile.files[0]);
    },
    onReaderLoad(event) {
        console.log(JSON.parse(event.target.result))
    }
}

It creates an instance of Filereader, add a callback for when finished reading the file and voilà!

Follow example code: https://codesandbox.io/s/vue-template-9swn8

Browser other questions tagged

You are not signed in. Login or sign up in order to post.