简体   繁体   中英

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":"johndoe@infosnap.com"}]

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: "johndoe@infosnap.com"
    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\": \"johndoe@infosnap.com\", \"$$hashKey\": \"004\"}]"

I am trying to get something like this...

[
  {
    "id": 2,
    "name": "John Doe",
    "email": "johndoe@infosnap.com",
    "$$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\": \"johndoe@infosnap.com\"}]"

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": "johndoe@infosnap.com"
}

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

Thanks!

You should parse the json instead of stringify.

Try this:

$scope.debug = JSON.parse(data)

Working Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM