【问题标题】:How to compare two jsons and return the unmatched objects using python如何使用python比较两个json并返回不匹配的对象
【发布时间】:2020-05-06 09:14:51
【问题描述】:

以下是示例输入 json 文件:

json1:

[
  {
    "App_Name": "hospital",
    "Instances": 1,
    "Memory": 256,
    "Disk_Quota": 1024
  },
  {
    "App_Name": "ecommerce",
    "Instances": 10,
    "Memory": 2048,
    "Disk_Quota": 1024
  },
  {
    "App_Name": "airlines",
    "Instances": 3,
    "Memory": 1024,
    "Disk_Quota": 1024
  }]

json2:

[
  {
    "App_Name": "bus",
    "Instances": 1,
    "Memory": 256,
    "Disk_Quota": 1024
  },
  {
    "App_Name": "hospital",
    "Instances": 10,
    "Memory": 2048,
    "Disk_Quota": 1024
  },
  {
    "App_Name": "govt",
    "Instances": 3,
    "Memory": 1024,
    "Disk_Quota": 1024
  }]

我需要比较两个 JSON 文件,并且需要将所有不匹配的应用名称对象返回到单独的变量中,例如

expected output: ================== 
unmatched objects in file = [{"App_Name": "ecommerce","Instances": 10,"Memory": 2048,"Disk_Quota": 1024},{"App_Name": "airlines","Instances": 3,"Memory": 1024,"Disk_Quota": 1024 }] 
unmatched objects in file2 = [{"App_Name": "bus","Instances": 1,"Memory": 256,"Disk_Quota": 1024},{"App_Name": "govt","Instances": 3,"Memory": 1024,"Disk_Quota": 1024}

【问题讨论】:

  • 你尝试了什么?您是否遇到我们可以帮助您解决的错误? SO 是一个问答网站,而不是代码工厂。
  • 预期输出:================== 文件中不匹配的对象 = [{"App_Name": "ecommerce","Instances": 10, "Memory": 2048,"Disk_Quota": 1024},{"App_Name": "airlines","Instances": 3,"Memory": 1024,"Disk_Quota": 1024 }] file2 中不匹配的对象 = [{"App_Name ": "bus","Instances": 1,"Memory": 256,"Disk_Quota": 1024},{"App_Name": "govt","Instances": 3,"Memory": 1024,"Disk_Quota": 1024}]
  • 请在您的问题中包含代码。 cmets 中未格式化的代码不可读。

标签: python json python-3.x


【解决方案1】:

将每个文件反序列化为以json.load为关键字的字典列表,将字典列表重构为以App_Name为键的嵌套字典。然后只需检查键是否存在于具有列表理解的其他字典中并将它们过滤掉。

from json import load

with open("json1.json") as json1, open("json2.json") as json2:
    json1dict = {d["App_Name"]: d for d in load(json1)}
    json2dict = {d["App_Name"]: d for d in load(json2)}

    unmatched1 = [v for k, v in json1dict.items() if k not in json2dict]
    print(unmatched1)

    unmatched2 = [v for k, v in json2dict.items() if k not in json1dict]
    print(unmatched2)

输出:

[{'App_Name': 'ecommerce', 'Instances': 10, 'Memory': 2048, 'Disk_Quota': 1024}, {'App_Name': 'airlines', 'Instances': 3, 'Memory': 1024, 'Disk_Quota': 1024}]
[{'App_Name': 'bus', 'Instances': 1, 'Memory': 256, 'Disk_Quota': 1024}, {'App_Name': 'govt', 'Instances': 3, 'Memory': 1024, 'Disk_Quota': 1024}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多