Retrieving information from a .json file using TypeScript

I am facing an issue with my Angular application. I have successfully loaded a .json file into the application, but getting stuck on accessing the data within the file. I previously asked about this problem but realized that I need help in specifically understanding how to access the data in a file that has already been uploaded and recognized as an application/json file by my application.


        startUpload(event: FileList){
            var file = event.item(0);
            console.log(file)
        }
    

console output


        File(139404) {name: "turnaroundtest.json", lastModified: 1527392751758, lastModifiedDate: Sat May 26 2018 20:45:51 GMT-0700 (PDT), webkitRelativePath: "", size: 139404}
    

Answer №1

To accomplish this task, follow these steps:

  checkFiles(e) {
    const selectedFiles = e.target.files;
    if (e.target.files && e.target.files[0]) {
      const filereader = new FileReader();
      filereader.onload = ((evt) => {
        const dataResult = evt.target['result'];
        console.log(JSON.parse(dataResult));
      });
      filereader.readAsText(e.target.files[0]);
    }
  }

Answer №2

give this a shot.

console.log('title' + data.title);
or

if (undefined !== responseData.title && null !== responseData.title){
    console.log('title' + responseData.title);
}

in case you are dealing with an array of json objects

for (const dataObject in responseData) {
    if (undefined !== responseData[dataObject].title && null !== responseData[dataObject].title) {
        console.log('title' + responseData[dataObject].title);
    }
}

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

Router navigation does not trigger LifeCycle calls

I currently have the following routes set up: {path:'home', component:HomeComponent, canActivate: [AuthGuard]}, {path:'profile', component:UserProfileComponent, canActivate: [AuthGuard] }, Additionally, in my navbar.component, I hav ...

Seeking a quick conversion method for transforming x or x[] into x[] in a single line of code

Is there a concise TypeScript one-liner that can replace the arrayOrMemberToArray function below? function arrayOrMemberToArray<T>(input: T | T[]): T[] { if(Arrary.isArray(input)) return input return [input] } Trying to cram this logic into a te ...

Fixing the forwardRef issue with react-router-dom and material-ui

Despite implementing the forwardRef as recommended in various posts and Material-UI website examples, I am still encountering a warning in the console that has me puzzled. I am working on setting up a drawer with a list of items that are React Router link ...

Include a fresh attribute within the existing JSONArray

My situation is as follows: "sections": [ { "id": XXXX, "tipology": "TIPOLOGY" }, { "id": XXXX, "tipology": "TIPOLOGY" }, {"num": 2} ], I am currently utilizing JSONArray and JSONObject. I ...

npm unable to locate a JavaScript file

Currently, I am developing an Angular 2 application that utilizes the ng2-slugify package. However, I have encountered an issue where it cannot locate one of the required slugify files, specifically "charmaps.js", even though it is stored in the same direc ...

Bypassing disputes in a TypeScript function

I attempted to implement the solution provided by Pacerier in response to the question about skipping arguments in a JavaScript function. However, it doesn't seem to be working for me. The function I am dealing with has numerous arguments. this.servi ...

Using Angular 6 pipes can simplify observable operations by eliminating the need for explicit typing

Recently, I upgraded my application from Angular5 to 6. Upon completing the update, I proceeded to migrate to rxjs6, which resulted in a change in my code where I was utilizing the takeWhile method. As a result, in order to subscribe to a service, my code ...

Unable to display animation without first launching it on Rive web

I attempted to incorporate a Rive animation into my Angular web application <canvas riv="checkmark_icon" width="500" height="500"> <riv-animation name="idle" [play]="animate" (load)=&qu ...

What is the method for sending a Post request using the "content type" value of "application/x-www-form-urlencoded"?

Need to send a request to the oAuth2 authentication server to obtain a token. The request works fine in postman but encountering issues when trying to make the same request from Angular 4. CORS configuration is correct as other requests are functioning p ...

Tips for retrieving data from Angular Material Table source

It's great to see everyone doing well! I'm facing an issue with rendering data to a material table, and I can't figure out why it's not working. When I try to assign the data to the table's datasource for rendering, the information ...

What is the process for implementing a version folder for my @types/definition?

Is there a way to access the typings for react-router in my project? My package.json file currently has this dependency: { "@types/react-router": "^4.0.3" } However, it seems to be using the standard index.d.ts file from DefinitelyTyped library which i ...

Unable to access /route upon refreshing page in Angular 7

After developing several components in Angular 7, I decided not to use 'useHash: true' for routing. Everything seemed to be running smoothly when I deployed my Angular app on a live server. However, I encountered an issue when reloading a page a ...

The error message "Property 'map' is not found on type 'User' in React with typescript"

I am currently experimenting with React using TypeScript. I have set up useState with an object but I am encountering issues trying to use the map function with that object. Below is the error message I am facing: Property 'map' does not exist ...

"Utilizing variadic tuple types to implement the pipe function in TypeScript 4: A step-by-step guide

An illustration from the release notes of TypeScript 4 demonstrates the use of variadic tuple types to eliminate multiple overload definitions. It seems feasible to type the pipe function for any number of arguments. type F<P, R> = (p: P) => R ty ...

Exploring Angular 2: How to Retrieve the Value of a Radio Button

How can I retrieve the value of the radio button that is clicked in app.component.html from within app.component.ts? app.component.html <div class="container"> <div class="row"> <div class="col-sm-3 well" style="width: 20%"> ...

I am interested in utilizing python-shell for handling json data, however, I am encountering issues with the python module

Being new to computer science, I am interested in learning how to manipulate JSON data using Python. On a NodeJS server, you can run a Python module like this: const data = {"uid":"XZsGi9A93NNH4fRYYI5a2Wk4Hfm1","lat":"37.5916983","lng":"127.012060400000 ...

Enhancing UI-Grid: Implementing Dynamic Field Addition in the Header Name Section

There is a grid with a field named Users, and the requirement is to display the count of Users in the header name of a ui-grid. How can I achieve this? This snippet shows my JavaScript file code: var userCount = response.usercount; columnDefs: [{ nam ...

Revising a conceivably intricate template

Let's talk about managing suppliers' documents, which include code, names, and various other fields. I currently have a component export class SuppliersDetails extends MeteorComponent { supplier: any; invalidKeys: Object; // array <key&g ...

Error message: An unhandled TypeError occurs when attempting to access properties of an undefined object (specifically, the 'then' property) while refreshing the token using axios

Is there a way to refresh tokens in axios without interrupting the flow? For example, when the server returns an access token expiration error, I want to queue the request and replay it after getting a new token. In React, I'm using promises as shown ...

The input of 'Response' does not match the expected type of 'string'

I am currently working on a project that involves retrieving books from the Google Book API using Angular 4. Although I am still learning Angular, I am facing challenges in understanding how to read the JSON response. During my research online, I came acr ...