Kevin
Kevin

Reputation: 2154

Angular JSON Filter for Array of Objects

I am using $http to fetch a collection of users. The raw response from the server is this...

[{"id":2,"name":"John Doe","email":"[email protected]"}]

Logging the data parameter in the success callback shows this...

[Object, each: function, eachSlice: function, all: function, any: function, collect: function…]
  0: Object
    $$hashKey: "004"
    email: "[email protected]"
    id: 2
    name: "John Doe"
    __proto__: Object
  length: 1
__proto__: Array[0]

Good enough. Looks like $http already de-serialized the raw JSON into a JavaScript object.

Next, I assign the data to a $scope variable, inside the success callback, in order to perform some debugging in the browser...

$scope.debug = data;

Now, in my view, I want to display this as pretty JSON in order to debug.

<pre>{{debug | json}}</pre>

And I get this...

"[{\"id\": 2, \"name\": \"John Doe\", \"email\": \"[email protected]\", \"$$hashKey\": \"004\"}]"

I am trying to get something like this...

[
  {
    "id": 2,
    "name": "John Doe",
    "email": "[email protected]",
    "$$hashKey": "004"
  }
]

I also tried to stringify the javascript array in the controller...

$scope.debug = JSON.stringify(data, true);

and not use the filter...

<pre>{{debug}}</pre>

but I get the same results, except the $$hashKey has been removed...

"[{\"id\": 2, \"name\": \"John Doe\", \"email\": \"[email protected]\"}]"

If I just assign the first item in the array to $scope, and use the json filter, it works fine...

$scope.debug = data[0];

In my view...

<pre>{{debug | json}}</pre>

Results in...

{
  "id": 2,
  "name": "John Doe",
  "email": "[email protected]"
}

I know there are other ways to get what I want. I am just trying to understand what is going on.

Thanks!

Upvotes: 1

Views: 2186

Answers (1)

D.Evangelista
D.Evangelista

Reputation: 6543

You should parse the json instead of stringify.

Try this:

$scope.debug = JSON.parse(data)

Working Fiddle

Upvotes: 1

Related Questions