2015-09-11 115 views
2

我想解析一個JSON文件,我爲我正在創建的應用程序創建。 JSON文件看起來是這樣的:用AngularJS解析JSON文件

{"thresholds":[ 
    {"heatIndex":[ 
     {"maxTemp":[{"red":"125","orange":"105","yellow":"90","green":"-80"}]}, 
     {"minTemp":[{"red":"-50","orange":"-35","yellow":"-20","green":"0"}]} 
    ]}, 
    {"wind":[ 
     {"speed":[{"red":"34.8","orange":"26.1","yellow":"17.4","green":"0"}]}, 
     {"gust":[{"red":"50.4","orange":"39.1","yellow":"26.1","green":"0"}]} 
    ]} 
]} 

我需要讓我的角度應用輸出的數據對我和一直在試圖遵循http.get教程,我不能讓我的數據出來。基本的一部分,我需要怎麼我的角度應用程序的該部分格式的幫助:在您的$ HTTP請求

<ul> 
    <li ng-repeat="x in thresholds"> 
     {{x.thresholds}} 
    </li> 
    </ul> 
    </div> 

    <!-- NG APP Script --> 
    <script> 
    var ehwo2App = angular.module('ehwo2App' , []); 
    ehwo2App.controller('ehwo2Ctrl' , function ($scope, $http) { 
     $http.get('config.json').success(function(data) { 
      $scope.thresholds = data; 
     }); 
     }); 
    </script> 
+0

$ scope.thresholds = JSON.parse(data); (因爲數據是即將到來的字符串我想)問你的朋友谷歌之前發佈問題http://stackoverflow.com/questions/4935632/parse-json-in-javascript –

+2

@DmitriAlgazin實際上你不必這樣做,角度自動爲你解析json。除非你知道你是對的,否則試着在評論時不要低估。 –

回答

1

,嘗試對其進行更改:

$scope.thresholds = data; 

$scope.thresholds = data.thresholds; 
+0

感謝兄弟。儘管如此,仍然不確定要進一步鑽取。例如,如果我想maxTemp:紅色值等... –

+0

我也有一個問題,記住這一點。我相信你應該可以像訪問JavaScript對象一樣訪問數據。所以最高臨時工將是$ scope.thresholds.heatIndex.maxTemp檢查了這一點https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects – Nibb

0

首先請注意,success快捷方式現在已被棄用,您應該使用標準.then方法(請參閱this page上的紅色方框。

其次,你還沒有說實話什麼確切地不起作用。嘗試使用下面的代碼,並讓我們知道在控制檯中記錄的內容。

ehwo2App.controller('ehwo2Ctrl' , function ($scope, $http) { 

    console.log("Making GET request"); 

    $http.get('http://www.dev.nids.noaa.gov/~mneedham/config.json') 

    .then(function(response) { 
    $scope.thresholds = response.data.thresholds; 
    console.log($scope.thresholds); 
    }) 

    .catch(function(error){ 
    console.error("Error with GET request", e); 
    }); 

});