繁体   English   中英

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

[英]how to get multiple keys from nested JSON in javascript?

我的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()方法时,当我控制nameR的值时,我得到一个错误“undefined”。 请建议我怎么做?

此函数接收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

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

// 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));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM