我想比较两个json文件,并通过python程序准备一个报告。 我使用了一个可用的库jsoncompare
我所尝试的:
from jsoncompare import jsoncompare as json_comp
json_comp.long = int
json_comp.unicode = str
json_comp.xrange = range
a = [
{
"Key": "Name",
"Value": "node1"
},
{
"Key": "owner",
"Value": "jhonson"
},
{
"Key": "managed",
"Value": "yes"
}
]
b = [
{
"Key": "Name",
"Value": "node1"
},
{
"Key": "owner",
"Value": "jhonson"
},
{
"Key": "managed",
"Value": "No"
}
]
# Compare respecting each array's order
json_comp.are_same(a, b)
print(json_comp.are_same(a, b)[1])
以上输出:
Reason: Different values
Expected:
"yes"
Actual:
"No"
Reason: Different values (Check order)
Expected:
{
"Key": "managed",
"Value": "yes"
}
Actual:
{
"Key": "managed",
"Value": "No"
}
当两个json都匹配时,我不会得到任何输出,但即使匹配,我也需要打印值,并在report中的差异(Yes或No)列中表示Yes
预期输出为表格格式(可能是html),例如:
逻辑:
1)value for key Name starts with lowercase + value match -- Yes
2)value for key Name starts uppercase but value matches -- No
3)for other keys When value does not match its - No
4)for other keys When value does match (irrespective of case) its - Yes
谁能提出更好的方法来做这件事,或任何参考资料。
如果你的钥匙是一样的,你可以在这里使用熊猫:
import pandas as pd
with open('a.json', 'r+') as f:
data_a = json.load(f)
with open('b.json', 'r+') as f:
data_b = json.load(f)
df_a = pd.json_normalize(data_a)
df_b = pd.json_normalize(data_b)
df = pd.merge(df_a, df_b, left_index=True, right_index=True)
df['diff'] = df['Value_x']==df['Value_y']
print(df)
Key_x Value_x Key_y Value_y diff
0 Name node1 Name node1 True
1 owner jhonson owner jhonson True
2 managed yes managed No False
您可以使用以下方法将其转换为html:
df.to_html('test.html')