比较两个JSON文件并更新修改

2024-04-24 22:52:04 发布

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

我正在处理一个需求,在这个需求中,我必须比较两个json文件(master.json和delta.json),如果master.json文件中的对象中的key:value对有任何更改,则更新对象

例如:

        **master.json**
       
        {
         [
           {
             host: abc
             IP  : 10.10.11.1
           }
           {
             host: def
             IP: 10.10.11.2
           }
          ]
         }

         **delta.json**
         {
          [ 
            {
             host: abc
             IP: 10.12.12.2
           }
          ]
         }

正如在delta.json中更改的主机IP地址示例中所示。此更新必须移动到master.json

生成的master.json应该是

       **master.json**
       
        {
         [
           {
             host: abc
             IP  : 10.12.12.2
           }
           {
             host: def
             IP: 10.10.11.2
           }
          ]
         }

Tags: 文件对象keyipmasterjsonhost示例
1条回答
网友
1楼 · 发布于 2024-04-24 22:52:04

使用JSON模块,我们可以从文件中解析JSON。 要用delta更新master,可以使用递归函数

import json

master = json.loads(open("master.json", 'r', encoding='utf-8').read())
delta = json.loads(open("delta.json", 'r', encoding='utf-8').read())

def iterate_paralell(delta, master):
    for k,v in delta.items():

        # if it's another dict or list run recursively
        if isinstance(v, dict): iterate_paralell(v, master[k])
        elif isinstance(v, list):
            for i in range(len(v)): iterate_paralell(v[i], master[k][i])
        
        # update the maste with delta value
        else:        
            master[k] = v

iterate_paralell(delta, master)

函数在delta对象上迭代,并在到达“叶”时通过将其作为参数传递来更新master

master.json

{
    "connections": [
        {
            "host": "abc",
            "IP": "10.10.11.1"
        },
        {
            "host": "def",
            "IP": "10.10.11.2"
        }
    ]
}

delta.json

{
    "connections": [
        {
            "host": "abc",
            "IP": "10.12.12.2"
        }
    ]
}

相关问题 更多 >