我有以下脚本输出json格式的对象:
function test() {
autoscaling.describeAutoScalingGroups(params, function(err, data) {
if (err) console.log(err, err.stack); // an error occurred
else console.log(JSON.stringify(data)); // successful response
});
}
test();
这输出以下json:
{
"ResponseMetadata": {
"RequestId": "##################"
},
"AutoScalingGroups": [
{
"AutoScalingGroupName": "################",
"AutoScalingGroupARN": "arn:aws:autoscaling:eu-west-1:#########:autoScalingGroup:###########",
"LaunchConfigurationName": "######-LC-###########",
"MinSize": 0,
"MaxSize": 0,
"DesiredCapacity": 0,
"DefaultCooldown": 300,
"AvailabilityZones": [
"eu-west-1b",
"eu-west-1c",
"eu-west-1a"
],
"LoadBalancerNames": [
"#########-ELB-###########"
],
"TargetGroupARNs": [
],
"HealthCheckType": "ELB",
"HealthCheckGracePeriod": 300,
"Instances": [
],
"CreatedTime": "2017-11-08T18:22:05.093Z",
"SuspendedProcesses": [
{
"ProcessName": "Terminate",
"SuspensionReason": "User suspended at 2017-11-08T18:22:14Z"
}
],
"VPCZoneIdentifier": "subnet-######,subnet-#######,subnet-#######",
"EnabledMetrics": [
],
"Tags": [
{
"ResourceId": "#######-ASG-##########",
"ResourceType": "auto-scaling-group",
"Key": "aws:cloudformation:logical-id",
"Value": "ASG",
"PropagateAtLaunch": true
},
{
"ResourceId": "#######-ASG-#########",
"ResourceType": "auto-scaling-group",
"Key": "aws:cloudformation:stack-id",
"Value": "arn:aws:cloudformation:eu-west-1:########:stack/##############",
"PropagateAtLaunch": true
},
{
"ResourceId": "################",
"ResourceType": "auto-scaling-group",
"Key": "aws:cloudformation:stack-name",
"Value": "#######",
"PropagateAtLaunch": true
}
],
"TerminationPolicies": [
"Default"
],
"NewInstancesProtectedFromScaleIn": false
}
]
}
我需要获得"SuspendedProcesses":[{"ProcessName"
的价值:(见上文)
然后,如果"ProcessName" == "Terminate"
的值(如上所述)执行此操作,则执行此操作。
我知道如何构造if else语法,但如何预先从JSON输出中建立"ProcessName"
的值?
我也知道如何操作在脚本中创建的数组,但我在这里遇到困难,因为json对象是由test()
函数创建的,所以正常的规则似乎不是应用
任何帮助将不胜感激。 感谢
答案 0 :(得分:0)
首先,使用return语句替换console.log()调用。那你就可以做到
var json = test();
var processes = json["AutoScalingGroups"][0]["Suspended Processes"]
更新代码:
function test() {
autoscaling.describeAutoScalingGroups(params, function(err, data) {
if (err) {
return [err, err.stack]; // an error occurred
} else {
var json = JSON.stringify(data); // successful response
return json["AutoScalingGroups"][0]["Suspended Processes"];
}
});
}
var processes = test()
console.log(processes);
答案 1 :(得分:0)
感谢@RobbieMilejczak,解决了问题:
首先,使用return语句替换console.log()调用。那你就可以做到
var json = test();
var processes = json["AutoScalingGroups"][0]["Suspended Processes"]
updated code:
function test() {
autoscaling.describeAutoScalingGroups(params, function(err, data) {
if (err) {
return [err, err.stack]; // an error occurred
} else {
var json = JSON.stringify(data); // successful response
return json["AutoScalingGroups"][0]["Suspended Processes"];
}
});
}
var processes = test()
console.log(processes);