bernardo
bernardo

Reputation: 23

How to access nested json property

I am getting this response from an angular service:

response.data
events: Array(1)
0:
ingestionTime: 1560362454013
message: "{"server":"xxx.xxx","errorName":"HelloWorldError","error":"hello error"}"
timestamp: 1560362450917

I save this response as:

$scope.accounts = response.data;

When printing in the html, nothing is displayed on the screen:

<tr ng-repeat="event in accounts.events track by $index">
        <td>{{event.message[1].errorName}}</td>
    </tr>

When I print like

{{event.message}} //it displays whole json string

But I need to access the json properties of message property like:

{{event.message.errorName}} //this is not priinting anything
{{event.message[1].errorName}} //this is not priinting anything

Anybody could give me some advice, i am new to angularJS :(?

Upvotes: 0

Views: 673

Answers (3)

Sagar Agrawal
Sagar Agrawal

Reputation: 657

The message attribute is stringified. It has to be parsed to access various attributes in it.

You could do this:

for(var i=0; i < $scope.accounts.events.length; i++){
   $scope.accounts.events[i].message = JSON.parse($scope.accounts.events[i].message);
}

And the way to use in HTML is like below. You don't need to put an index with message (event.message[1].errorName). This is wrong. Either you put an attribute or the index where the attribute is present. Else it will give you undefined. My recommendation is not use index of the attribute but the attribute like event.message.errorName .. because it is more readable. Example below:

<tr ng-repeat="event in accounts.events track by $index">
    <td>{{ event.message.errorName }}</td>
</tr>

Upvotes: 0

Soujanya Divi
Soujanya Divi

Reputation: 97

In the above response, event.message is a string, its not an JSON object. So, you were unable to parse it.

Convert string to JSON object using

var obj = JSON.parse(string);

Upvotes: 0

georgeawg
georgeawg

Reputation: 48968

If each message is JSON string, they can be parsed to JavaScript objects:

$scope.accounts = response.data;
$scope.accounts.events.forEach( _ => _.messageObj = JSON.parse(_.message));

Then display with:

<tr ng-repeat="event in accounts.events">
    <td>{{event.messageObj.errorName}}</td>
</tr>

Upvotes: 0

Related Questions