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

How to get single specific values for keys in json structure?

本文关键字:单个特 结构 json 何获取 获取      更新时间:2023-09-26

我正在做一些练习,比如:

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]
}

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

尝试

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

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

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/

运行此程序并查看它是否生成您想要的内容:

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

只有一行代码用于迭代密钥和分配:

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

像这样尝试

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>