简体   繁体   English

如何在JavaScript中解析JSON响应?

[英]How to parse json response in javascript?

After making a call to rest api I am getting this data in javascript. 调用rest api后,我正在javascript中获取此数据。

{
  "error": false,
  "orders": [
    {
      "oid": "764",
      "cid": "423",
      "name": "Akshay jain",
      "address": "infront of gwal magra talab",
      "mobile": "11111111",
      "email": "abcd@gmail.co",
      "odate": "2016-03-28 21:50:45",
      "status": "NEW ORDER",
      "payment": "1",
      "ddate": "2016-03-28",
      "dtime": "1"
    },
    {
      "oid": "763",
      "cid": "438",
      "name": "Vishwakarma Ji",
      "address": "Narayan Pura Road",
      "mobile": "0000000000",
      "email": null,
      "odate": "2016-03-28 20:02:06",
      "status": "Confirmed (Ready for Delivery)",
      "payment": "1",
      "ddate": "2016-03-28",
      "dtime": null
    }
  ]
}

This is how i am storing in controller. 这就是我在控制器中存储的方式。

$scope.result = Order.query(); // where Order is a service in angularjs

If i am trying to print $scope.result.error it is giving object object not the actual error value. 如果我尝试打印$ scope.result.error,它给的是object对象而不是实际的错误值。

How to parse error and orders in javascript and save it in a variable? 如何解析JavaScript中的错误和顺序并将其保存在变量中?

If this Order.Query is async, you have to set the result in a callback 如果此Order.Query是异步的,则必须在回调中设置结果

app.controller("OrderIndexCtrl",function($scope,Order) {
  Order.query(function(data){
     if(data.error == false) {
        $scope.result = data.orders;
     }
     else {
        ...
     }
  });
});

Try using the following code. 尝试使用以下代码。

$scope.result = JSON.parse(Order.query());

Source: this question 资料来源: 这个问题

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

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