将数据从JSON文件加载到Javascript对象

时间:2016-01-02 23:31:38

标签: javascript angularjs json

我正在尝试访问我的JSON文件中的数据,以便在 我的控制器中使用Angular进行进一步操作。首先,这是文件' cards.json'

的前几个条目
{ "TheGrandTournament": [
{
  "name": "Buccaneer",
  "cardSet": "The Grand Tournament",
  "type": "Minion",
  "rarity": "Common",
  "cost": 1,
  "attack": 2,
  "health": 1,
  "text": "Whenever you equip a weapon, give it +1 Attack.",
  "collectible": true,
  "playerClass": "Rogue",
  "img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_029.
},
{
  "name": "Competitive Spirit",
  "cardSet": "The Grand Tournament",
  "type": "Spell",
  "rarity": "Rare",
  "cost": 1,
  "text": "<b>Secret:</b> When your turn starts, give your minions +
  "collectible": true,
  "playerClass": "Paladin",
  "img": "http://wow.zamimg.com/images/hearthstone/cards/enus/original/AT_073.
  "mechanics": [{"name": "Secret"}]
}, ...
]}

我已成功使用此代码访问我的视图中的信息

<div ng-controller="CardCtrl">
    <button id="loadbtn" ng-click="load()">Load</button><br>
    <div ng-repeat="cards in data.TheGrandTournament | limitTo:2">
        <pre>{{ cards.name }}</pre>
    </div>
</div

我的控制器看起来像这样:

angular.module('cards', []).controller('CardCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $scope.method = 'GET';
        $scope.url = 'cards.json';

        $scope.load = function() {
            $scope.code = null;
            $scope.response = null;

            $http({method: $scope.method, url: $scope.url}).
                then(function(response) {
                    $scope.data = response.data;
                    console.log("Read file", $scope.url, "successfully.");
                }, function(response) {
                    $scope.data = response.data || "Request failed";
                    console.log("Error reading", $scope.url, ".");
                });
        };

        $scope.cardData = angular.fromJson($scope.data[0]);
        console.log($scope.cardData);

    }]);

尝试将$ scope.cardData输出到控制台日志时返回的错误是

"TypeError: Cannot read property '0' of undefined". 

我尝试使用angular.fromJson()从json对象解析数据,但它不能正常工作。

3 个答案:

答案 0 :(得分:1)

替换: $ scope.data = response.data;

使用: $ scope.data = response.data.TheGrandTournament;

答案 1 :(得分:1)

您应该将$scope.data移动到承诺的成功回调中:

$http({method: $scope.method, url: $scope.url}).
  then(function(response) {
    $scope.cardData = response.data.TheGrandTournament;
    console.log("Read file", $scope.url, "successfully.");
    console.log($scope.cardData);
  }, function(response) {
    $scope.data = response.data || "Request failed";
    console.log("Error reading", $scope.url, ".");
  });
    // scope parameter data is not accessible here, as it's not yet added
    //$scope.cardData = angular.fromJson($scope.data[0]);
    //console.log($scope.cardData);

}]);

答案 2 :(得分:0)

尝试替换:

$scope.cardData = angular.fromJson($scope.data[0]);

使用:

$scope.cardData = angular.fromJson($scope.data["TheGrandTournament"][0]);