简体   繁体   English

对象数组的角度JSON过滤器

[英]Angular JSON Filter for Array of Objects

I am using $http to fetch a collection of users. 我正在使用$ http来获取用户集合。 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. 看起来$ http已经将原始JSON反序列化为JavaScript对象。

Next, I assign the data to a $scope variable, inside the success callback, in order to perform some debugging in the browser... 接下来,我将数据分配给成功回调中的$ scope变量,以便在浏览器中执行一些调试...

$scope.debug = data;

Now, in my view, I want to display this as pretty JSON in order to debug. 现在,在我看来,我想将其显示为漂亮的JSON以便进行调试。

<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... 我也试图在控制器中对javascript数组进行字符串化处理。

$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... 但是我得到了相同的结果,除了$$ hashKey已被删除...

"[{\"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,并使用json过滤器,则效果很好...

$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. 您应该解析json而不是stringify。

Try this: 尝试这个:

$scope.debug = JSON.parse(data)

Working Fiddle 工作小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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