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

Learn how to showcase JSON information using the `vis.js` library

I am working on displaying data from MySQL using vis.js. I have successfully retrieved the data in JSON format, but I keep encountering the following error: Error: Node must have an id throw new Error("Node must have an id"); -------^ function ...

Angular/Karma Unit Test for HttpClient

During my research on unit testing, I came across some very useful examples. Most of the examples focus on unit testing functions that interact with Angular's HttpClient, and they usually look like this: it('should return an Observable<User[] ...

Encountered an issue in Laravel 5.7 JSONResource toArray method: Declaration must be compatible

I'm encountering an issue while trying to use the JSON Resource to Array converter in Laravel. Here is a snippet of my code: DataResource.php <?php namespace App\Http\Resources; use Illuminate\Http\Request; use Illuminate&bso ...

Drizzle ORM retrieve unique string that is not a database column

I'm working with a SQL query that looks like this: SELECT * FROM ( SELECT 'car' AS type, model FROM car UNION SELECT 'truck' AS type, model FROM trucks ) vehicles; In Drizzle, I'm trying to replicate the 'car ...

A method for sorting an array of characters based on the numerical values within

Can someone help me organize this vector of chr in numerical order? x=c("class 1", "class 2", "class 4", "class 7", "class 5", "class 3", "class 6", "class 10", "class 9", "class 11", "class 8", "class 12", "class 21") I want the result to be ordered by ...

Turning ResultSet into a json object in Restlet framework: A step-by-step guide

After executing a query on a table, I now have a ResultSet object: ResultSet result = stat.executeQuery("SELECT * FROM Greetings"); I am looking to convert this ResultSet object into JSON format and send it back to the web client. Can a Restlet tool be u ...

Make a POST request using Express API, supporting both JSON and XML data

I am facing a unique challenge with my express API. While it typically accepts JSON post requests, there is one particular API that requires an XML post body instead. To set up my express app accordingly, I have used the following configuration: // Init ...

No data found in the subrow of the datasource after the filter has been

I am working with a material table that has expandable rows. Inside these expanded rows, there is another table with the same columns as the main table. Additionally, I have implemented filters in a form so that when the filter values change, I can update ...

Nested loops - I'm on the brink of success, but there's a minor flaw in this code

I am currently working on a function that takes two arrays of strings as input from another function. The goal is to compare each element in the first array with every element in the second array and determine if they are equal in length. Let x represent ...

Difficulty with navigation buttons on multiple Bootstrap carousels implemented using ngFor in a single page

Currently, I'm engaged in developing a practice eCommerce platform where multiple product cards are showcased using data from a sample JSON file. Additionally, several Bootstrap carousels are integrated into the website to display images of each item. ...

Add CSS styling to a particular div element when a button is clicked

I have been working on a new feature that involves highlighting a div in a specific color and changing the mouse pointer to a hand cursor. I successfully achieved this by adding a CSS class: .changePointer:hover { cursor: pointer; background-color ...

Adding a dynamic click event in HTML using IONIC 4

I've created a function using Regex to detect URL links and replace them with a span tag. The replacement process is working fine, but I'm facing an issue where when I include (click)="myFunction()" in the span, it doesn't recognize the cli ...

How can I prevent node_module from being included when using the include directive in tsconfig.json?

Many developers are excluding the node_modules folder in their tsconfig.json. I, on the other hand, am using the include directive with specific folder patterns. Do I really need to exclude node_modules? And what about third-party libraries that aren' ...

Is there a way to retrieve the address value from a JSON object using PHP?

I have the following JSON data and I need help extracting each address value and storing them in a comma-separated string. Array ( [ResponseCode] => 0 [ResponseMessage] => OK [ResponseDateTime] => 5/6/2017 11:46:05 AM GMT [Data] => A ...

Convert a TextView into a JSON Object

I'm currently in the process of scanning a QR code that provides me with data displayed in a textview. Is there a way for me to convert this data into a JSON object? It seems like a challenging task, but I need to transform the multiple data points wi ...

Limit the scope of a custom range on a list of strings

Is there a way to determine if the elements of my array let actualSigns = ["Aa", "Bb", "Cc"] ... are identical to any of the arrays within this collection... var validSigns = [[String]]() validSigns.append(["Aa", "Bb", "Cc", "Dd"]) // hoping to find a m ...

Retrieve the value from a checkbox using Flask and then transfer the extracted data to a different template

I am currently working with Weasyprint to showcase some Jinja templates within a Flask Web App. Here is the JSON data I am using: value=["1","2","3","4"] My goal is to pass the 'value' variable to another Jinja template within an if statement. ...

Warning: NG2 RC5 has deprecated the use of HTTP_PROVIDERS

With the release of Angular2 version RC5, there have been some changes such as deprecating HTTP_PROVIDERS and introducing HttpModule. While my application code is functioning properly with this change, I am facing difficulties in updating my Jasmine tests. ...

The jquery datatable is not properly receiving the Json response

I am looking to dynamically populate a jQuery datatable with different sets of data based on the request parameter. I have received the object JSON response, but I'm encountering an error when trying to bind it to the datatable. DataTables warning: t ...

The Primeng badge feature fails to detect changes in severity

Within my primeng application, there is an icon featuring a badge that is structured as follows: <i (click)="showAllNotifications()" class="pi pi-bell mr-3 p-text-secondary" pBadge style="font-size: 2rem" [value]=&q ...