Is there a way to extract data from a JSON file using the readfile function in Vue?

I am having trouble reading a JSON file's content. I attempted to access the contents using ReadFile, but I was not successful. The content string is empty and the URL is undefined.

Here is my code:

<template>
 <div class="large-12 medium-12 small-12 cell">
   <input type="file" accept="application/JSON" @change="onFileChange" class="inputFile" />
 </div>
</template>

<script>
import Vue from "vue";

export default {
 data() {
   return {};
 },
 methods: {
   onFileChange(e) {
     let files = e.target.files || e.dataTransfer.files;
     if (!files.length) return;
     this.readFile(files[0]);
   },
   readFile(file) {
     let reader = new FileReader();
     reader.onload = e => {
       this.readContentFile = e.target.result;
       console.log(this.readFile);
     };
     let url = reader.readAsDataURL(file);
     let content =reader.result;
     console.log(url);
     console.log(content);
   }
 }
};
</script>

Answer №1

Just missed it by a hair. The function reader.onload acts as a callback after the file has completed loading, meaning any console.logs placed before it may run prematurely. This snippet should steer you in the right direction.

new Vue ({
 el: "#app",
 methods: {
   onFileChange(e) {
     let files = e.target.files || e.dataTransfer.files;
     if (!files.length) return;
     this.readFile(files[0]);
   },
   readFile(file) {
     let reader = new FileReader();
     reader.onload = e => {
       console.log(e.target.result);
       let json = JSON.parse(e.target.result);
     };
     reader.readAsText(file);
   }
 }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div class="large-12 medium-12 small-12 cell" id="app">
   <input type="file" accept="application/json" @change="onFileChange">
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Saving div data to a database using Ajax techniques

I have a project where I need to store div content in a database. The content looks like this: <span>name:</span><input type="text" id="inputid" value="John"><br /> To fetch this content successfully, I used innerHTML method and s ...

Having trouble formatting JSON data in a jQuery datatable with accurate information

Currently, I am diving into the world of jQuery tables specifically for a report that I am working on. Despite successfully receiving the API response, I am facing challenges in binding it to the jQuery datatable. I have searched through various questions ...

What is causing my controller action to create two new records instead of just one?

My current issue involves a simple Razor view featuring a button designed to add a new record to a table within my SQL database. The button is equipped with an Ajax function that triggers a call to the controller. I've experimented with two different ...

Is there a way to enable scanned data to be automatically inputted into a field without manual entry?

I am in the process of creating a user-friendly Android app for virtual inventory management. I want the application to streamline data input by automatically populating text fields upon scanning, eliminating the need for users to manually click on each fi ...

PHP Instant Chat Improvements

I am in the process of developing a messaging system that consists of the following components: A form that allows users to send messages, with PHP handling the insertion of data into a MySQL Table named userMessages upon submission. A PHP page that ...

The dropdown on my website is malfunctioning

There seems to be an issue with my dropdown button. Previously, it only appeared when clicking on a specific part of the button. I attempted to resolve this problem but unfortunately, the dropdown no longer works at all and I am unable to revert my changes ...

Prevent User Access to Start Button During Browser Request Processing

I have buttons for starting and stopping a window service on a server. When I click on the start button, the service takes some time to start. During this time, I need to disable the start button on the client side. The same goes for the stop button. Even ...

Dynamically fetching data with Node.js using Ajax requests

Despite my efforts to scour Google and Stack Overflow, I have been unable to find a reliable method for posting data to my Node.js server. I've noticed conflicting information on various methods, likely due to changes over time. One particular code ...

Selecting the first li element using JQuery selectors

Can anyone help me with creating an onclick event that triggers when the user clicks on the first list item which is labeled as "Any Date"? I am looking to use jQuery to target this specific element. <ul id="ui-id-1" class="ui-menu ui-widget ui-widge ...

Retrieve a collection of composite entities using Jersey ClientResponse

I am attempting to retrieve a List of entities using Jersey RESTful API (both Server and Client). UserRESTClient client = new UserRESTClient(); ClientResponse response = client.getUsersByType(ClientResponse.class, String.valueOf(userType)); List<User&g ...

Problem with deleting or substituting symbols and character codes within a String

I am attempting to send an object called dataO from Node.js/Express/EJS to the client side. On the Node.js script side: var dataO = {"first":[20000, 14000, 12000, 15000, 18000, 19000, 22000], "second":[12000, 11000, 18000, 12000, 19000, 14000, 26000]}; var ...

To interact with a specific cell in a table using Protractor, simply click

I have a dataset containing various elements such as images, text, and numbers. I am struggling to click on a specific text within the dataset. As someone new to e2e testing with Protractor, any assistance would be greatly appreciated. I specifically need ...

Develop a starting point for creating a schedule

Currently, I am working on a project involving a MongoDB database. Specifically, I have a collection of books and I am in need of implementing some statistics logic related to user reading behavior. Essentially, I need to track the start time of when a use ...

Retrieve a key from the JSON response and then transmit it through a socket

In the context of a node server code using a monitoring module to track function properties, I am facing an issue where I need to retrieve a specific property from a JSON output and then transfer it to a socket. The function 'meter' looks like t ...

Ways to restrict the character count in a form input field

I need to limit characters in an input box on a form to 140, but I am struggling to figure out how to do it. Using Angular on the front end. The code for the input section where I need a text limit is in new.html <div class="form-group"> <lab ...

Should I release an Aurelia component on NPM?

Our team has developed a compact Aurelia application and now we are looking to seamlessly incorporate it into a larger codebase. One possible scenario is distributing the Aurelia app on NPM to allow other projects to easily integrate our code. What steps ...

The limitations of Typescript types influence the program's behavior

As a newcomer to the Typescript environment, I am currently developing a test application to familiarize myself with it. However, I have encountered an issue regarding type restrictions that seems to be not working as expected. In my class, I have defined ...

The Evolution of Web Applications with AJAX

Introduction: We have a webapp in classic ASP that is becoming increasingly difficult to maintain as it grows. The complexity of the code and the numerous ASP pages required are hindering our ability to develop new features. I believe it's time we mo ...

The duplicate code is failing to display any output

Welcome to my first question here! Please excuse any rookie mistakes. I am currently working on a specialized calculator using HTML, JS (with jQuery), and CSS. This calculator is designed to handle multiple inputs and perform various calculations on a sing ...

Does the date() function in Node.js return the server-side date or the client-side date?

As a beginner in Node JS, I have a question regarding the behavior of Date(). If I use Date() in my Node.js code, will it return the server-side date or will it behave like regular JavaScript where Date() gives the client PC date? I am curious to know ho ...