Devesh Agrawal
Devesh Agrawal

Reputation: 9212

How to parse json response in javascript?

After making a call to rest api I am getting this data in javascript.

{
  "error": false,
  "orders": [
    {
      "oid": "764",
      "cid": "423",
      "name": "Akshay jain",
      "address": "infront of gwal magra talab",
      "mobile": "11111111",
      "email": "[email protected]",
      "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.

How to parse error and orders in javascript and save it in a variable?

Upvotes: 0

Views: 116

Answers (2)

George Chen
George Chen

Reputation: 6959

If this Order.Query is async, you have to set the result in a callback

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

Upvotes: 2

Imesha Sudasingha
Imesha Sudasingha

Reputation: 3570

Try using the following code.

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

Source: this question

Upvotes: 0

Related Questions