如何在angularJS中以对象形式解析AJAX Json数据

How can I parse AJAX Json data in object form in angularJS

本文关键字:AJAX 数据 Json 对象 angularJS      更新时间:2023-09-26

这是我的JSON数据Content.json

[{
    status: "Allocated",
    count: 45
}, {
    status: "Bench",
    count: 89
}, {
    status: "Mobile",
    count: 12
}, {
    status: "Project",
    count: 1
}, {
    status: "SAP",
    count: 18
}, {
    status: "Testing",
    count: 68
}, {
    status: "vvvv",
    count: 70
}];

尝试获取JSON文件

angular.module('myApp')
 .controller('valueController', ['$scope', '$http', '$window', function ($scope, $http, $window) {
var mainInfo = null;
  $http({
    method : "GET",
    url : "/JSON/Content.json",
    dataType: 'json',
  }).then(function mySucces(response) {
     $scope.mainInfo = response.data;
      $window.alert(response.data);
    }, function myError(response) 
    {
      $window.alert(response.statusText);
  });

$scope.chartOptions = {
            dataSource: mainInfo,       
            series: {
                argumentField: "status",
                valueField: "count",
                name: "SIDG Java",
                type: "bar",
                color: '#1899dd'
            }
        };
}]);

在alert中我得到:

Localhost: 8080说:

[{
    status: "Allocated",
    count: 45
}, {
    status: "Bench",
    count: 89
}, {
    status: "Mobile",
    count: 12
}, {
    status: "Project",
    count: 1
}, {
    status: "SAP",
    count: 18
}, {
    status: "Testing",
    count: 68
}, {
    status: "vvvv",
    count: 70
}];

我期待的是

Localhost: 8080说:

[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],

通过实现代码,我在警报中获得[object,object][object,object][object,object]。请再次检查JSON。

如果需要使用[object,object]结构

,可以使用JSON.parse(response.data)解析数据

有可能AngularJS无法在响应数据中检测到JSON。可能是响应中的Content-Type标头不是application/json ?

你可以尝试用responseType: 'json'替换$http配置中的dataType: 'json',告诉AngularJS预测JSON响应。

要在警报中显示,使用json将其转换为json字符串。stringify函数。