正在将JSON文件中的数据加载到Javascript对象中

Loading data from JSON file in to Javascript object

本文关键字:加载 Javascript 对象 数据 JSON 文件      更新时间:2023-09-26

我正在尝试访问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对象中的数据,但它并没有按我的意图工作。

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

$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);
}]);

替换:$scope.data=响应数据;

与:$scope.data=response.data.TheGrandTournament;

尝试替换:

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

带有:

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