Python中的Foreach循环从JSON响应中的数组中提取值

时间:2018-07-25 22:19:14

标签: python powershell

我有这个json响应:

{
    "properties": {
        "basic": {
            "bandwidth_class": "",
            "failure_pool": "",
            "max_connection_attempts": 0,
            "max_idle_connections_pernode": 50,
            "max_timed_out_connection_attempts": 2,
            "monitors": [
                "Simple HTTP"
            ],
            "node_close_with_rst": false,
            "node_connection_attempts": 3,
            "node_delete_behavior": "immediate",
            "node_drain_to_delete_timeout": 0,
            "nodes_table": [
                {
                    "node": "abc1.prod.local:80",
                    "priority": 1,
                    "state": "active",
                    "weight": 1
                },
                {
                    "node": "def1.prod.local:80",
                    "priority": 1,
                    "state": "disabled",
                    "weight": 1
                },
                {
                    "node": "ghi1.prod.local:80",
                    "priority": 1,
                    "state": "disabled",
                    "weight": 1
                },
                {
                    "node": "jkl1.prod.local:80",
                    "priority": 1,
                    "state": "active",
                    "weight": 1
                }
            ],
            "note": "",
            "passive_monitoring": true,
            "persistence_class": "",
            "transparent": false
        }
    }
}

此powershell脚本:

$nodesAarray = "abc1.prod.local:80", "jkl1.prod.local:80"
foreach($node in $nodesArray)
{
    $nodes_match_and_enabled = $GetNodesResponse.properties.basic.nodes_table | Where { $_.node -eq $node -and $_.state -eq "active" }
    if($nodes_match_and_enabled)
    {
        Write-Output "$node exists in the pool and active"
    }
    else 
    {
        Write-Output "$node is either not active or the name mismatches"
        $global:invalidNodeArray.Add($node)     
    }
}

在powershell脚本中,我循环检查数组中的两个节点实际上是否按值匹配,并且状态为活动。它按我的预期工作。

但是,我正在用Python编写完全相同的逻辑脚本(我是一个初学者),但是不确定如何实现它。知道脚本在Python中的样子了吗?

3 个答案:

答案 0 :(得分:0)

我认为应该可以在Python 2或3中工作

#!/usr/bin/env python

import sys
import json

res = ""
for line in sys.stdin:
  res += line.rstrip()

res_obj = json.loads(res)

nodes = [ 'abc1.prod.local:80', 'jkl1.prod.local:80' ]

invalid_nodes = []

for node in nodes:
  try:
    found = False
    test_node_objs = res_obj['properties']['basic']['nodes_table']
    for test_node_obj in test_node_objs:
      test_node = test_node_obj['node']
      if node == test_node:
        found = True
        break
    if found:
      sys.stdout.write("%s exists in the pool and active\n" % (node))
    else:
      sys.stdout.write("%s is either not active or the name mismatches\n" % (node))
      invalid_nodes.append(node)
  except KeyError as ke:
    sys.stderr.write("malformed response? check input...\n")
    pass

用法示例:

$ ./parse_response.py < response.json

答案 1 :(得分:0)

这是一个实现:

jsonObj = json.loads(jsonSrc)

expectedNodes = {"abc1.prod.local:80", "jkl1.prod.local:80"} 

for node in expectedNodes:
    node_table = jsonObj['properties']['basic']['nodes_table']

    node_match = list(filter(lambda t_node: node == t_node['node'], node_table))
    is_node_matches_and_active = len(node_match) > 0 and node_match[0]['state'] == "active"
    if is_node_matches_and_active:
        print('node {} exists and is active'.format(node))
    else:
        print('node {} not found or not active'.format(node))

输出:

node jkl1.prod.local:80 exists and is active
node abc1.prod.local:80 exists and is active

答案 2 :(得分:0)

首先,过滤所有活动节点,然后与节点列表进行比较:

resource "aws_spot_instance_request" "PrimaryDC" {
  wait_for_fulfillment = true

  provisioner "local-exec" {
    command = "aws ec2 create-tags --resources ${self.spot_instance_id} --tags Key=Name,Value=${var.ServerName}0${count.index +01}"
  }

  ami                    = "ami-629a7405"
  spot_price             = "0.01"
  instance_type          = "t2.micro"
  count                  = "${var.count}"
  key_name               = "${var.KeyPair}"
  subnet_id              = "${var.Subnet}"
  vpc_security_group_ids = ["${var.SecurityGroup}"]
  get_password_data      = "true"

  user_data = <<EOF
  <powershell>
  Rename-computer -NewName "${var.ServerName}0${count.index +01}"
  </powershell> 
  EOF

  tags {
    Name = "${var.ServerName}0${count.index +01}"
  }
}

output "PW" {
 value = "${element(concat("${aws_spot_instance_request.PrimaryDC.*.password_data}", list("")), 0)}"
}

output "DCPWUn" {
 value = "${element(concat("${rsadecrypt(aws_spot_instance_request.PrimaryDC.*.password_data,file("${var.PATH_TO_PRIVATE_KEY}"))}", list("")), 0)}"
}