如何在javascript中从嵌套的JSON中获取多个键?

时间:2017-02-16 20:26:10

标签: javascript angularjs json

我的JSON就像:

{
  "boundaries": [
    {
      "boundary": {
        "boundaryId": "45083021141",
        "boundaryType": "USA_POSTCODE",
        "boundaryRef": "B1"
      }
    }
  ],
  "themes": [
    {
      "TheftCrimeTheme": {
        "boundaryRef": "B1",
        "individualValueVariable": [
          {
            "name": "2013 Theft Crime",
            "description": "Theft Crime for 2013",
            "count": 2080
          }
        ]
      }
    },
    {
      "BurglaryCrimeTheme": {
        "boundaryRef": "B1",
        "individualValueVariable": [
          {
            "name": "2013 Burglary Crime",
            "description": "Burglary Crime for 2013",
            "count": 302
          }
        ]
      }
    }
  ]
}

我希望获得计数值以在图表中显示。正如您在上面的json中所看到的,内部主题有两个键,即TheftCrimeTheme和BurglaryCrimeTheme。我想在everycrimeheme中获得数值。为此,我做了以下代码:

 $http.get("http://152.144.218.70:8080/USACrime/api/crimeAPI?city="+$scope.strCity+"&crimeType="+$scope.type1+"&years="+$scope.type+"&month="+$scope.type2).success(function (result) {  
   for(var i=0;i<result.themes.length;i++){
                      var crime={};
                        console.log("did",result.themes[i]);
                      var test2 = result.themes[i];
                      console.log("test2",test2);
                      var test = test2[Object.keys(test2)];
                      console.log("test",test);
                      crime.name = Object.keys(result.themes[i]);
                      console.log("CrimeName",crime.name);
                      crime.data = [];
                      var test1 = test.individualValueVariable[0].count;
                      console.log("test1",test1);
                      crime.data.push(test1);
                      crime_data.push(crime);
                    }

    });

我的议程是绘制图表,显示每年的数量。要实现这一点,我必须得到多个键,如TheftCrimeTheme,BurglaryCrimeTheme等。然后我可以访问个人值的计数值。 当我使用Object.keys()方法时,我收到错误&#34; undefined&#34;当我控制nameR的值时。请建议我该怎么做?

2 个答案:

答案 0 :(得分:0)

此函数接收info(作为整个json),theme作为您想要计算的主题(即:"BurglaryCrimeTheme")。

getThemeCrimesCount = (info, theme) => {
    const record = info.themes.find(obj => Object.keys(obj)[0] == theme)[theme];
    return record.individualValueVariable.reduce((a, b) => a += b.count, 0);
}

getThemeCrimesCount(info, "BurglaryCrimeTheme"); // 302
getThemeCrimesCount(info, "TheftCrimeTheme"); // 2080

答案 1 :(得分:0)

为了清晰起见,将其格式化以分隔元素。

// Builds and returns URL with query string attached.
const buildURL = (uri, params) => {
  let queryParams = Object.keys(params).map(function(k) {
      return encodeURIComponent(k) + '=' + encodeURIComponent(params[k])
  }).join('&');
  return uri + '?' + queryParams;
};

// Parses returned JSON object.
const parseStatistics = (result) => {
  // My assumption here is that you are receiving a JSON string, which 
  // would need to be parsed into an object before being used.
  let result = JSON.parse(result);

  // Set base object
  let namR = {};

  // Iterate through themes array.
  result.themes.forEach(function(element) {
    // Find the object name for current theme.
    let type = Object.keys(element)[0];

    // Find count for current theme.
    let count = element[type].individualValueVariable.count;

    // Set count.
    namR[type] = count;
  });

  // Log object
  console.log(namR);
};

// Set up url info.
let params = {
  city: $scope.strCity,
  crimeType: $scope.type1,
  years: $scope.type,
  month: $scope.type2
};
let baseURL = "http://152.144.218.70:8080/USACrime/api/crimeAPI";

// Execute request.  
$http.get(buildURL(baseURL, params)).success(parseStatistics(response));