比较2个Json文件并显示第二个文件的差异

时间:2019-06-27 13:25:49

标签: python json

这些是我拥有的两个json文件 JSON1.json

{

  "name": "HOSTNAME1",

  "chef_environment": "non_prod",

  "run_list": [

    "role[MyOrg-non_prod]",

    "role[rhel7-latest]",

    "role[middleware-nonprod-all]",

    "role[MyApp-middleware_corebase_prod]",

    "role[MyApp_envs-test]",

    "role[MyApp_envs-dev]",

    "role[MyApp_nfs_mount]",

    "role[MyApp_access-dev]",

    "role[MyOrg-client-wrapper]"

  ]

}

JSON2.json

{

  "name": "HOSTNAME2",

  "chef_environment": "non_prod",

  "run_list": [

    "role[MyOrg-non_prod]",

    "role[rhel7-latest]",

    "role[MyApp_unix_app-dev]",

    "role[MyApp_middleware_corebase_prod]"

  ]

}

这些文件可能会排序,也可能不会排序。我需要获取JSON1唯一的值JSON1

我最初使用类似的命令

findstr /vig:JSON1.json JSON2.json  | grep -v name| grep -e MyApp -e MyOrg | tr -d '\n'| sed -e 's:"::g' -e 's: *::g'  -e 's:,$::'

无论如何,请考虑例如 在JSON1中,我有一个条目 “角色[MyApp_middleware_corebase_prod]”,

和JSON2中 “角色[MyApp_middleware_corebase_prod]”

请注意逗号之间的差异,尽管条目是相同的,因此不是唯一的,但是由于逗号的存在,这被认为是唯一的,并给了我不希望的输出。

如果我比较JSON1与JSON2,则预期输出为 角色[MyApp_unix_app-dev] 因为这是JSON2唯一的

如果我比较JSON2和JSON1

角色[MyApp_envs-test],角色[MyApp_envs-dev],角色[MyApp_nfs_mount],角色[MyApp_access-dev],角色[MyOrg-client-wrapper]

2 个答案:

答案 0 :(得分:2)

设置减法(差异)是我真正想要的:

import json


with open('json1.json', 'r') as f:
    json1 = json.load(f) 

with open('json2.json', 'r') as f:
    json2 = json.load(f) 

json2['run_list'] = list(set(json2['run_list']) - set(json1['run_list']))

print(json.dumps(json2, indent=2))

输出:

{
  "name": "HOSTNAME2",
  "chef_environment": "non_prod",
  "run_list": [
    "role[MyApp_unix_app-dev]"
  ]
}

答案 1 :(得分:1)

您可以使用python设置交集

json1 = {

      "name": "HOSTNAME1",

      "chef_environment": "non_prod",

      "run_list": [

        "role[MyOrg-non_prod]",

        "role[rhel7-latest]",

        "role[middleware-nonprod-all]",

        "role[MyApp-middleware_corebase_prod]",

        "role[MyApp_envs-test]",

        "role[MyApp_envs-dev]",

        "role[MyApp_nfs_mount]",

        "role[MyApp_access-dev]",

        "role[MyOrg-client-wrapper]"

        ]

       }

json2={

          "name": "HOSTNAME2",

          "chef_environment": "non_prod",

          "run_list": [

            "role[MyOrg-non_prod]",

            "role[rhel7-latest]",

            "role[MyApp_unix_app-dev]",

            "role[MyApp_middleware_corebase_prod]"

          ]

        }
set1 = set(json1['run_list'])
set2 = set(json2['run_list'])
set3 = set1.intersection(set2)