python-3.x - how to compare to two json files and return a un matched key and value in object
问题描述
JSON File1:
[{
"App_Name": "Test1",
"Instances": "2",
"Memory": "2G",
"Disk_Quota": "1G"
}, {
"App_Name": "Test2",
"Instances": "2",
"Memory": "2G",
"Disk_Quota": "1G"
}, {
"App_Name": "Test3",
"Instances": "1",
"Memory": "1G",
"Disk_Quota": "1G"
}]
JSON file2:
[ {
"App_Name": "Test3",
"Instances": "1",
"Memory": "1G",
"Disk_Quota": "5G"
},{
"App_Name": "Test1",
"Instances": "3",
"Memory": "2G",
"Disk_Quota": "1G"
}, {
"App_Name": "Test2",
"Instances": "2",
"Memory": "8G",
"Disk_Quota": "1G"
}]
I have to compare both the JSON files and need to print the unmatched value from the JSON objects.
So far I have tried this one
def Compare():
with open("Jsonfile1.json") as f:
data = f.read()
env1 = json.loads(data)
with open("jsonfile2.json") as f:
data = f.read()
env2 = json.loads(data)
for name in env1:
for names in env2:
if name['App_Name'] == names['App_Name']:
if name['Instances'] != names['Instances']:
print("unmatched val {} -i {}".format(name['App_Name'],names['Instances']))
if name['Memory'] != names['Memory']:
# print(name['Memory'], names['Memory'])
print("unmatched val {} -m {}".format(name['App_Name'],names['Memory']))
if name['Disk_Quota'] != names['Disk_Quota']:
print("unmatched val {} -k {}".format(name['App_Name'],names['Disk_Quota']))
Compare()
Excepted output :
if there is a mismatch in instance then print(jsonfile1 instance value) if there is a mismatch in memory then print(jsonfile1 memory value) if there is a mismatch in disk then print(jsonfile1 disk value)
解决方案
这应该做的工作:
for d1 in env1: # Iterate over all dictionaries in first JSON
# Look for the corresponding dictionary in second JSON
candidates = [d for d in env2 if d["App_Name"] == d1["App_Name"]]
if not candidates:
print(d1) # If no corresponding dict, just print and go to next
else:
d2 = candidates[0] # If corresponding dict, look for mismatches
for key in d1:
if d1.get(key) != d2.get(key): # Find mismatches
print(f"mismatch detected for app='{d1['App_Name']}'")
print(f"\tenv1's value for key='{key}' is {d1.get(key)}")
print(f"\twhile env2's value for key='{key}' is {d2.get(key)}")
输出:
mismatch detected for app='Test1'
env1's value for key='Instances' is 2
while env2's value for key='Instances' is 3
mismatch detected for app='Test2'
env1's value for key='Memory' is 2G
while env2's value for key='Memory' is 8G
mismatch detected for app='Test3'
env1's value for key='Disk_Quota' is 1G
while env2's value for key='Disk_Quota' is 5G
推荐阅读
- android - 条目名称“res/color/material_on_surface_disabled.xml”发生冲突
- python - Plotly:如何避免使用 go.Heatmap 对 x 和 y 类别进行分组?
- javascript - 如何使用 Angular 中的 Tab 键从 mat 下拉列表中选择一个选项
- c++ - 在 C++ 上运行简单的二进制搜索时遇到问题
- javascript - 如何在查询函数中返回数据
- phpmyadmin - raspbian busetr 上的 phpmyadmin 无法登录
- oracle - Oracle SYSDBA 连接
- rust - 如何强制 `async_std` 任务在 rust 的单个线程上运行?
- azure - 使用 Azure 前门时缺少 UserId 属性的应用程序见解
- java - 如何使用 Pattern 和 Matcher 使程序输出整个单词