首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Python中的Foreach循环从json响应中的数组中提取值

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

Stack Overflow用户
提问于 2018-07-26 06:19:14
回答 3查看 169关注 0票数 -2

我得到了这个json响应:

代码语言:javascript
复制
{
    "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脚本:

代码语言:javascript
复制
$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中会是什么样子吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2018-07-26 06:52:46

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

代码语言:javascript
复制
data = json.loads(text)
active_nodes = {
    n['node']
    for n in data['properties']['basic']['nodes_table']
    if n['state'] == 'active'
}

nodes = {"abc1.prod.local:80", "jkl1.prod.local:80"}
for node in nodes:
    if node in active_nodes:
        print('{} exists in the pool and active'.format(node))
    else:
        print('{} is either not active or the name mismatches'.format(node))

invalid_nodes = nodes - active_nodes
票数 0
EN

Stack Overflow用户

发布于 2018-07-26 06:27:28

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

代码语言:javascript
复制
#!/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

示例用法:

代码语言:javascript
复制
$ ./parse_response.py < response.json
票数 0
EN

Stack Overflow用户

发布于 2018-07-26 06:35:00

下面是一个实现:

代码语言:javascript
复制
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))

输出:

代码语言:javascript
复制
node jkl1.prod.local:80 exists and is active
node abc1.prod.local:80 exists and is active
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51528461

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档