asp
asp

Reputation: 835

How to compare two json file and print report of differences

I would like to compare two json files and prepare a report via python program. I used one of library which was available called jsoncompare

What I have tried:

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])

Output of above:

  Reason: Different values
Expected:
  "yes"
Actual:
  "No"

Reason: Different values (Check order)
Expected:
  {
      "Key": "managed",
      "Value": "yes"
  }
Actual:
  {
      "Key": "managed",
      "Value": "No"
  }

When both json matches then I am not getting any output, but even if matches, i need to print values and say Yes in Difference(Yes or No) column in report

Expected output in table format possibly html for example :

enter image description here

logic:

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

can some one suggest any better ways to do that, or any reference please.

Upvotes: 2

Views: 3290

Answers (1)

NYC Coder
NYC Coder

Reputation: 7594

If your keys are the same, you can use pandas here:

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'] = np.where((df['Key_x']=='Name') & (df['Value_x'].str.contains(r'^[a-z]')) & (df['Value_y'].str.contains(r'^[a-z]'))  & (df['Value_x']==df['Value_y']), 'No', 'Yes')
df['diff'] = np.where((df['Key_x']!='Name') & (df['Value_x']!=df['Value_y']), 'Yes', 'No')
print(df)

     Key_x  Value_x    Key_y Value_y diff
0     Name    node1     Name   node1   No
1    owner  jhonson    owner  wright  Yes
2  managed      yes  managed      No  Yes

You can convert this to html using:

df.to_html('test.html')

Upvotes: 1

Related Questions