2014-07-03 78 views
1

這是一個我真正感到愚蠢的問題。但是我搜索了網頁,並沒有找到具體的例子來解決我的問題。幸運的是,這個問題很簡單。我已被AngularJS閱讀下面的JSON數據如下:無法解析AngularJS中的特定JSON數據

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

    return roles; 
    }); 

在這種情況下,控制檯輸出如下:

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

我期望roles包含具有這些數字的陣列,然而,當我打印出roles的值,它只是表示[object Object]

如何訪問results陣列中包含的數字?

非常感謝!

+0

你嘗試打印爲:'JSON.stringify(response.data)'? –

+1

'response.data'是您所需要的。在添加'angular.fromJson'調用時,您將有效地創建另一個對象,並從JSON響應反序列化。 – Ben

回答

2

JavaScript數組也是一個對象,所以也許你這麼做的時候,你var roles = angular.fromJson(response.data).model.results;得到了你想要的陣列。嘗試的角色[1]

+0

這確實是答案。我發誓我嘗試了十億次。這是編程,我猜:)。感謝您的幫助! – insomniac

+0

感謝您的回答!我搜索了網頁,發現每個人都使用JSON.parse,但不幸的是,這並沒有奏效。你的答案完美無缺。 – nkt24

0

不要嘗試從JSON「加載」一個JSON對象。

response.data已經JSON格式的角度轉化..只要使用它像:

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

當我嘗試這樣做時,會發生以下情況:第一行​​輸出'undefined',第二行導致TypeError:無法讀取未定義的屬性'結果' – insomniac

+0

如果console.log(response.data)返回帶有'模型'鍵,它應該肯定會工作... –

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); 


    }); 

    } 

});