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

时间:2019-08-04 15:07:00

标签: python json ansible

我正在尝试创建一个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'] }

1 个答案:

答案 0 :(得分:0)

最后我这样解决了;

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始终返回“无”。因此,我必须在调试后删除pprint,而且我也使用了太多的循环。