1

This is a question I truly feel stupid for asking. But I have searched the web and haven't found a specific example with my problem. Luckily, the question is simple. I have the following JSON data being read in by AngularJS as follows:

return $http.post('getData.htm').then(function(response) {
    console.log("response.data: " + response.data);
    var roles = angular.fromJson(response.data).model.results;

    return roles;
  });

The console in this scenario outputs the following:

 response.data: {"model":{"results":["1","2","3","4","5","6","7","8","9","10","11"],"totalCount":11}}

I expect roles to contain an array with those numbers, however when I print out the value of roles it simply says [object Object].

How do I access the numbers contained in the results array?

thanks a lot!

2
  • Did you try to print as: JSON.stringify(response.data)? Commented Jul 3, 2014 at 11:36
  • 1
    response.data is all you need. In adding the angular.fromJson call, you're effectively creating another object, deserialized from the JSON response. Commented Jul 3, 2014 at 11:47

3 Answers 3

2

A javascript Array is also an Object so maybe when you did var roles = angular.fromJson(response.data).model.results; you got the array you wanted. Try roles[1]

Sign up to request clarification or add additional context in comments.

2 Comments

This was indeed the answer. I swear I tried this a billion times. That's programming, I guess :). thank you for the help!
Thanks for that answer!! I searched the web and found everyone using JSON.parse but unfortunately that didn't worked. Your answer worked perfectly.
0

Don't try to "load from JSON" a JSON object.

response.data is already transformed in JSON format by angular.. Just use it like that :

console.log(response.data.model);
console.log(response.data.model.results);
console.log(response.data.model.results[1]);

2 Comments

When I try this, the following occurs: The first line outputs undefined and the second causes TypeError: Cannot read property 'results' of undefined
if console.log(response.data) returns you an object with a 'model' key, it should definitely work...
0

http://jsbin.com/duruy/1/edit

app.controller('firstCtrl', function($scope, $http){

activate();
  $scope.roles = [];

function activate ()
  {

    return $http.get('http://jsbin.com/yewefo/1').then(function(response) {
    console.log(response.data.model);
   angular.copy(response.data.model.results, $scope.roles);


  });

  }

});

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.