如何从函数返回所有元素?

2024-03-28 16:30:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试创建一个Ansible模块,在Ansible剧本中使用Batfish。你知道吗

我将JSON值与函数中定义的变量进行比较。但是它只能比较函数中的一个JSON值和变量。如何使用循环和返回?你知道吗

我已经尝试从每个JSON中提取值,并尝试与定义的变量进行比较。你知道吗

import json
json_list = {"batfish_result": [
        {
            "Action": {
                "0": "DENY"
            },
            "Line_Content": {
                "0": "no-match"
            }
        },

       {
            "Action": {
                "0": "PERMIT"
            },
            "Line_Content": {
                "0": "permit    10.20.0.0 255.255.255.0"

            }
       }
     ]
   }


def main(json_list):
    PASS = 'PASS'
    FAIL = 'FAIL'
    result = {}
    result_list = []
    action_num_list = []
    condition_list = ['permit', 'permit']


    jsons = json_list["batfish_result"]
    for j in jsons:
        print(j)
        action = j['Action']
        action_num = action["0"]
        action_num_list.append(action_num)

    for con in condition_list:

          for action in action_num_list:

            if action == con.upper():

                result_list.append(PASS)
                result['msg'] = result_list

            else:

                result_list.append(FAIL)
                result['msg'] = result_list

    return result

main(json_list)

它回来了

{'msg': ['PASS', 'PASS']}

它应该像这样比较每个操作和每个条件变量。你知道吗

{ "msg": ['FAIL', 'PASS'] }

Tags: injsonforactionmsgpassresultansible
1条回答
网友
1楼 · 发布于 2024-03-28 16:30:24

最后我就这样解决了

import json
from pprint import pprint

json_list = {"batfish_result": [
        {
            "Action": {
                "0": "DENY"
            },
            "Line_Content": {
                "0": "no-match"
            }
        },

       {
            "Action": {
                "0": "PERMIT"
            },
            "Line_Content": {
                "0": "permit    10.20.0.0 255.255.255.0"

       }
  }
]
            }


def main(json_list):
    PASS = "PASS"
    FAIL = "FAIL"
    result = {}
    result_list = []
    action_num_list = []
    condition_list = ["permit", "permit"]

    jsons = json_list["batfish_result"]

    for j in jsons:
        action = j['Action']
        action_num = action["0"]
        action_num_list.append(action_num)
        #[DENY, PERMIT]

    for con in condition_list:
         con = con

    #for action in action_num_list:
    for x, y in zip(condition_list, action_num_list):

        if y == x.upper():

            result_list.append(PASS)
            result['msg'] = result_list

        #if pprint(y) != pprint(x.upper()):
        else:

            result_list.append(FAIL)
            result['msg'] = result_list

    return result_list

main(json_list)

因为pprint总是返回“None”。所以我不得不在调试之后删除pprint,而且我使用了太多的循环。你知道吗

相关问题 更多 >