Issue
I get following JSON Data from a back-end webservice.
[
{
"id": 10,
"name": "My Name1",
"age": 25,
"jsonData": null
},
{
"id": 15,
"name": "My Name2",
"age": 25,
"jsonData": "{\"Address\":\"My Address 123\",\"City\":\"My City\",\"PostalCode\":\"ABC-123-DEF\",\"Country\":\"My Country\"}"
}
]
I can loop the array on component html with ngFor without problem, but how do I read the "jsonData" fields like "Address", "City" etc.?
Thank you for the answer!
my API call from component.ts is like this:
async getAllUsers() {
this.allUsers = [];
this.allUsers = await lastValueFrom(
await this.service.getAllUsers()
);
this.allUsers.forEach((node) => {
node.jsonData = JSON.parse(node.jsonData);
});
}
then in my html I do like this:
{{ node.jsonData.Address }}
Solution
You need to convert the jsonData
from string
to object type with JSON.parse(<JSON string>)
.
Note that this can be performed during the returning Observable
/response via the map
(RxJS) operator.
Note that your jsonData
is possibly null
, so you have to check the jsonData
is truthy before converting.
import { map } from 'rxjs';
this.http.get<any[]>('<API URL>').pipe(
map((resp: any[]) =>
resp.map((x: any) => ({
...x,
jsonData: !!x.jsonData ? JSON.parse(x.jsonData) : null,
}))
)
);
Answered By - Yong Shun
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.