How to access nested json property

655 Views Asked by At

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 :(?

3

There are 3 best solutions below

0
georgeawg On

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>
0
Soujanya Divi On

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);
0
Sagar Agrawal On

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>