Using Angular to parse intricate JSON data

Need help parsing an http request in the following format:

[
    {
        "id": 1,
        "date": "2022-01-13T00:00:00.000+00:00",
        "time": "2022-01-13T21:21:21.000+00:00",
        "office": {
            "id": 2,
            "description": "Office2",
            "phone": "123456789",
            "enabled": 1
        },
        "officeDescr": "Office2",
        "reason": 2,
        "reasonDescr": "Studies",
        "file": "1.pdf",
        "status": 0,
        "userIn": {
            "username": "name",
            "password": "'$2a$04$DR/f..s1siWJc8Xg3eJgpeB28a4V6kYpnkMPeOuq4rLQ42mJUYFGC",
            "enabled": 1,
            "firstname": "fname",
            "lastname": "lanme",
            "asm": 123,
            "office": 2,
            "authorities": [
                {
                    "authority": "ROLE_POLITIS"
                }
            ]
        },
        "commentIn": null,
        "userValid": null,
        "commentValid": null,
        "userApproved": null,
        "commentApproved": null
    },
    ...
]

Having trouble extracting the username from the userIn object using:

    this.applicationService.get().subscribe(
      (applications) => (console.log(applications.body.find(s=>s.userIn).userIn)));

Is there a way to access the attributes separately?

Attempted adding brackets [] to

applications.body.find(s=>s.userIn).userIn
but always returns undefined.

EDIT
Utilizing a service that relies on HttpClient to fetch data from the Backend server

  getPostponements(): Observable<HttpResponse<Application[]>> {
    const url = `${this.apiUrl2}/postponements`;
    return this.http.get<Application[]>(url,{ observe: 'response' })
  }

The applications type within the .subscribe is

 HttpResponse<Application[]>

Included a Model named Application.ts:

export interface Application {
    id?: number;
    date: string;
    time: string;
    reason: number;
    reasonDescr: string;
    office: number;
    officeDescr: string;
    file: string;
    userIn: number;
    commentIn: string;
    userValid: string;
    commentValid: string;
    userApproved: string;
    commentApproved: string;
    status: number;
}

Answer №1

As mentioned by @GetOffMyLawn in the comment, it was pointed out that there was an issue with your model for the userIn.

When using Json2Ts, the structure of the Application class should be as follows:

export interface Office {
  id: number;
  description: string;
  phone: string;
  enabled: number;
}

export interface Authority {
  authority: string;
}

export interface UserIn {
  username: string;
  password: string;
  enabled: number;
  firstname: string;
  lastname: string;
  asm: number;
  office: number;
  authorities: Authority[];
}

export interface Application {
  id: number;
  date: Date;
  time: Date;
  office: Office;
  officeDescr: string;
  reason: number;
  reasonDescr: string;
  file: string;
  status: number;
  userIn: UserIn;
  commentIn?: any;
  userValid?: any;
  commentValid?: any;
  userApproved?: any;
  commentApproved?: any;
}

Additionally, if you need to retrieve information related to the userIn, adjustments to the logic are necessary. (Since specific details about which userIn's username are not provided, I have outlined some methods for your reference.)

To retrieve the username of the first item under userIn within an Application (Suggested by @GetOffMyLawn's comment)

applications.body[0].userIn.username

Obtain the username of a specific userIn based on the id of the corresponding Application

applications.body.find((x) => x.id == /* applicationId */).userIn.username

List all usernames of the userIns

applications.body.map(
  (x: Application) => x.userIn.username
)

Explore Sample Demo on StackBlitz

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

Occasional TypeError when receiving JSONP response using jQuery .ajax()

Occasionally, I encounter an error message stating Uncaught TypeError: undefined is not a function when processing the JSONP response from my jQuery .ajax() call. The JSON is returned successfully, but sometimes this error occurs during the reading process ...

Include a novel item into the JSON string that is being received

Recently, I attempted to parse an incoming JSON string and insert a new object into it. The method I used looked like this: addSetting(category) { console.log(category.value); //Console.log = [{"meta":"","value":""}] category.value = JSON.parse(c ...

"Mastering the Art of Bootstrapping Providers in Angular 2

Currently using rc2, I have a TypeScript file named config that I want to access throughout my application. To achieve this, I bootstrapped it in my main.ts like this: bootstrap(MyDemoApp, [ provideForms(), disableDeprecatedForms(), APP_ROUTER_PROVIDERS ...

The error message "Google Heatmap API - visualization_impl.js:2 Uncaught (in promise) TypeError: Cannot read property 'NaN' of undefined" was encountered while using the

I'm currently working on a project that involves utilizing a JSON data structure like the one shown below: [ { "lat": 53.1522756706757, "lon": -0.487157731632087, "size": 63, "field": "TestField", ...

Looking to reallocate information, paginate, and sort each time a new row is added to the mat-table

In my application, I have a customized <mat-table> with an implemented addRow() function that adds a new row to the table using default values based on the data type. The challenge I'm facing is that each time a new row is added, I find myself ...

Angular: Leveraging real-time data updates to populate an Angular Material Table by subscribing to a dynamic data variable in a service

Seeking guidance on how to set up a subscription to a dynamic variable (searchData - representing search results) for use as a data source in an Angular Material Table. I have a table-datasource.ts file where I want to subscribe to the search results from ...

What is the best way to utilize project references with multiple tsconfig files?

Let's say I have three separate projects to work on: shared frontend backend In order to use the shared project as a reference in both the frontend and the backend, I need to make a few adjustments. The backend utilizes commonjs modules while the fr ...

Navigating the world of NestJs and TypeScript with the `mongoose-delete` plugin: a comprehensive guide

I am currently utilizing Mongoose within the NestJs library and I want to incorporate the mongoose-delete plugin into all of my schemas. However, I am unsure of how to implement it with nestJS and Typescript. After installing both the mongoose-delete and ...

Order Varchar Data Array in Ascending Order using PHP

Is there a way to use PHP code to sort an array of varchar data in ascending order? I attempted it myself and the current result is : ABC1 ABC10 ABC11 ABC11A ABC11B ABC2 ABC2A ABC20 ABC3 However, my desired output is : ABC1 ABC2 ABC2A ABC3 ABC10 ABC11 A ...

Accessing a value within a JSON body response can be done by utilizing the Request module to send GET requests to an external API

Recently, I started working on a project using Express and Node.js to build a simple API that fetches data from an external source. When I run the code provided below and input my /api/posts/tech endpoint into Insomnia, I get back a response containing a J ...

Is there a way to display this JSON data using mustache.js without needing to iterate through a

Here is the JSON data: var details = [ { "event": { "name": "txt1", "date": "2011-01-02", "location": "Guangzhou Tianhe Mall" } ...

Mastering the Art of Adding Headers in Angular

Here is the Angular service code: getCareer(dataout: any){ let headers = new HttpHeaders().append('Content-Type', 'application/json').append('Authorization','Bearer'+' '+GlobalService.authToken); //hea ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...

Angular HTTP post is failing on the first attempt but succeeds on the second try

Just started working on my first Angular exercise and encountered an issue where I am receiving an undefined value on the first attempt from an HTTP post request. However, on the second try, I am getting the proper response in Edge and Firefox. Thank you f ...

What's the best way to serialize a NumPy array without losing its matrix dimensions integrity?

numpy.array.tostring does not retain information about the dimensions of the matrix (refer to this question), leading users to use numpy.array.reshape. Is there a method to serialize a numpy array into JSON format while keeping this information? Note: Th ...

How to prevent ConcurrentModificationException while converting to Json format?

In our project, we have a custom class called Document that utilizes a private member of type Map<String, Object> to store data. These objects are stored in memory and often modified by multiple threads. Additionally, these objects, particularly the ...

Handling a JSON exception of missing value for "opening_hours" in Java's org.json library. How to effectively manage this

logcat screenshot **after parsing the JSON, if there is no value for opening_hours, nothing is displaying. How to handle that? Please help me. url="https://maps.googleapis.com/maps/api/place/details/json?placeid=ChIJoTjQ-EC_wjsRjC-0kVQOIg0&key=API_KEY ...

Why is the "&" symbol in my JSON showing as "&amp;" when displayed in an Angular view?

In my project, I am utilizing a json file to store key/strings for localization with angular-translate. One of the strings in this file is 'Profile & Preferences', which I am using in my view. However, when I use ng-bind-html to display this ...

Enforcing object keys in Typescript based on object values

I'm looking to design a structure where the keys of an object are based on values from other parts of the object. For example: type AreaChartData = { xAxis: string; yAxis: string; data: { [Key in AreaChartData['xAxis'] | AreaChart ...

attempting to employ a custom class for storing a JSON reply

I am currently working on creating a Java class that will store a JSON response structured like this: { "Global Quote": { "01. symbol": "IBM", "02. open": "160.0000", "03. h ...