第一个JSON
{
"x": 10.1,
"y": 20,
"name": "Anu",
"dob": "2010-10-10"
}
JSON2
{
"x": 10,
"y": 20,
"name": "Ani",
"dob": "2010-10-11",
“z”:100
}
JSON结果{
"x": 0.1,
"name": "Text change",
"dob": "1"
"z": "Only in 2"
}
所以我尝试将json字符串转换为使用json的字典。加载函数,然后使用deepdiff获取字典之间的差异,但它给我的输出是字典中发生了什么变化,而不是上面提到的期望输出。
这是一种方法
from datetime import datetime
# load your d1 and d2
output_dict = {}
for k1 in d1.keys():
if k1 not in d2.keys():
output_dict[k1] = "only in 1"
for k2 in d2.keys():
if k2 not in d1.keys():
output_dict[k2] = "only in 2"
# I used seperate for loops above because using them in the zip didn't work
# due to the different sizes of the dicts, I believe there is a better solution
# than my double for loop
for k1, v1 in d1.items():
if (isinstance(v1, int) or isinstance(v1, float)) and (isinstance(d2[k1], int) or isinstance(d2[k1], float)):
if v1 - d2[k1] != 0:
# Use abs here if you want absolute difference
output_dict[k1] = round(v1 - d2[k1], 2)
elif isinstance(v1, str) and isinstance(d2[k1], str):
try:
v1_date = datetime.strptime(v1, "%Y-%m-%d")
v2_date = datetime.strptime(d2[k1], "%Y-%m-%d")
date_diff = v1_date - v2_date
output_dict[k1] = abs(date_diff.days)
except ValueError:
if v1 != d2[k1]:
output_dict[k1] = "Text change"
print(output_dict)