首页 > 解决方案 > 比较两个 JSON 文件并更新修改

问题描述

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

例如:

        **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
           }
          ]
         }

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

结果 master.json 应该是

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

标签: pythonjsoncompare

解决方案


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

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在它到达“叶子”时通过将其作为参数传递来更新它。

大师.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"
        }
    ]
}

推荐阅读