【问题标题】:Comparing two JSON files and update the modification比较两个 JSON 文件并更新修改
【发布时间】:2020-10-06 20:30:54
【问题描述】:

我正在处理一个要求,其中我必须比较两个 json 文件(master.json 和 delta.json 并在主对象中的任何键:值对有任何更改时更新对象) .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
           }
          ]
         }

【问题讨论】:

  • 我建议不要使用open(file),而是使用内置的Python JSON library
  • 这些示例 JSON 无效,数组需要属性,键必须是字符串,并且没有逗号。

标签: python json compare


【解决方案1】:

使用 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,方法是将其作为参数传递。

ma​​ster.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"
        }
    ]
}

【讨论】:

  • 感谢@Jesper Hustad 的回复和修改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-17
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
相关资源
最近更新 更多