如何获取json结构中键的单个特定值?

时间:2016-04-19 10:21:31

标签: javascript jquery arrays angularjs json

我正在做一些运动:

var jsonres;
jsonres = JSON.stringify(jsonObjectArray);
alert(jsonvals); // getting the below json structure

jsonres = {
    "key01": [10, "Key01 Description"],
    "key02": [false, "It's a false value"],
    "key03": [null, "Testing Null"],
    "key04": ["tests", "Another Test Value"],
    "key05": [[25, 50], "Some testing values"]
}

但我需要:

jsonres = {
    "key01": 10,
    "key02": false,
    "key03": null,
    "key04": "tests",
    "key05": [25,50]
}

我怎样才能获得上述结构(意味着我只需要单个值,不需要相应键的第二个值/多个值)?请帮助我,并提前感谢。

5 个答案:

答案 0 :(得分:3)

尝试

for(var key in jsonres) {
    jsonres[key] = jsonres[key][0];
}

这是一个小提琴https://jsfiddle.net/Lzb1dum3/

答案 1 :(得分:1)

只需一行代码来迭代密钥并分配:

var jsonres = {
    "key01": [10, "Key01 Description"],
    "key02": [false, "It's a false value"],
    "key03": [null, "Testing Null"],
    "key04": ["tests", "Another Test Value"],
    "key05": [[25, 50], "Some testing values"]
}

Object.keys(jsonres).forEach(function (k) { jsonres[k] = jsonres[k][0]; });
document.write('<pre>' + JSON.stringify(jsonres, 0, 4) + '</pre>');

答案 2 :(得分:1)

试试这个

var editer = angular.module('editer', []);
function myCtrl($scope) {
$scope.jsonres = {
  "key01": [10, "Key01 Description"],
  "key02": [false, "It's a false value"],
  "key03": [null, "Testing Null"],
  "key04": ["tests", "Another Test Value"],
  "key05": [[25, 50], "Some testing values"]
} 

angular.forEach($scope.jsonres, function(value,key){
      $scope.jsonres[key] = value[0];
  });

console.log($scope.jsonres);
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="editer" ng-controller="myCtrl" class="container">
  
  <pre >{{jsonres|json}}</pre>
</div>

答案 3 :(得分:1)

运行此命令并查看它是否生成了您想要的内容:

var jsonres = {
  "key01": [10, "Key01 Description"],
  "key02": [false, "It's a false value"],
  "key03": [null, "Testing Null"],
  "key04": ["tests", "Another Test Value"],
  "key05": [[25, 50], "Some testing values"]
} 

for (var key in jsonres) {
  jsonres[key] = jsonres[key][0];
  alert(jsonres[key]);
}

答案 4 :(得分:1)

var jsonres = {
    "key01": [10, "Key01 Description"],
    "key02": [false, "It's a false value"],
    "key03": [null, "Testing Null"],
    "key04": ["tests", "Another Test Value"],
    "key05": [[25, 50], "Some testing values"]
}

for(var key in jsonres){
   if(jsonres.hasOwnProperty(key)){
      jsonres[key] = jsonres[key][0];
   }
}

console.log(jsonres)

https://jsfiddle.net/xd4nwc0m/