为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Python 中比较两个 Json 数组?

如何在 Python 中比较两个 Json 数组?

明月笑刀无情 2023-01-04 13:32:23
我正在创建一个脚本,该脚本允许将两个 ssh 命令输出与远程 Netapp 进行比较,并且允许在当前值和 Netapp 机舱具有的最大空间值之间进行比较。我已经在两个字典(rv 和 rv 2)中收集了这些值,然后我将它们转换为 JSON 格式,以便能够根据传递给它的警告参数来比较它们(如果超过这个限制,它就会通知)。我想比较的值的示例: RV1:{'node1.storePool_Owner': ['160'], 'node1.storePool_Deleg': ['0'], 'node2.storePool_LockState': ['0']}RV2:{'node1.storePool_Owner': ['1024000'], 'node1.storePool_Deleg': ['1024000'], 'node2.storePool_LockState': ['1024000']}这个想法是将这些值中的每一个与它们的最大等效值进行比较。非常感谢你的帮助。应该如何比较的一个例子: 如果这个节点,具有那个值:node1.storePool_Owner': ['160']达到以下的 X%(警告 arg):node1.storePool_Owner': ['1024000']然后它应该返回:WARNING: node1.storePool_Owner has exceeded the threshold (x%)
查看完整描述

1 回答

?
慕无忌1623718

TA贡献1744条经验 获得超4个赞

这将比较两个 json 文件/字典。我注意到这些值是字符串列表......这是故意的吗?


import json



def open_json(path):

    with open(path, 'r') as file:

        return json.load(file)



def check_thresholds(data, thresholds):

    for k, v in thresholds.items():

        # your logic/output here

        # k[0] and v[0] because your values are lists of strings... should they be just int of float?

        difference = int(data.get(k)[0]) - int(v[0])

        if difference >= 0:

            print(f'WARNING: {k} has exceeded the threshold by {difference}')

        else:

            print(f'OK: {k}')



def main():

    # load the data into dictionaries

    data = open_json('./rv.json')

    thresholds = open_json('./rv2.json')


    # if your data is a dictionary and not json files then use these

    # data = {'node1.storePool_Owner': ['160'], 'node1.storePool_Deleg': ['0'], 'node2.storePool_LockState': ['0']}

    # thresholds = {'node1.storePool_Owner': ['1024000'], 'node1.storePool_Deleg': ['1024000'], 'node2.storePool_LockState': ['1024000']}


    # run the checks

    check_thresholds(data, thresholds)



main()


输出(我修改了一些值以显示警告):


WARNING: node1.storePool_Owner has exceeded the threshold by 1000

OK: node1.storePool_Deleg

OK: node2.storePool_LockState


查看完整回答
反对 回复 2023-01-04
  • 1 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信