Home > Blockchain >  Is there a good, controllable way to compare two .json files and generate their difference into an E
Is there a good, controllable way to compare two .json files and generate their difference into an E

Time:10-12

I have tried using jsondiff but the output was not upto my requirements.

with open('C/abc/file1.json') as f:
        a= json.load(f)
    
    with open('C/abc/file2.json') as s:
        b= json.load(s)
    c= diff(a,b)

What I want to print in Excel sheet is Delta, the things which are present in file1 but not in file2, present in file1 but changed in file2, newly added things in file2 that are not in file1 and if possible then line number too. So if anyone got any idea how to achieve this, then please share it and if need more clarifications then plzz let me know.

I cannot paste the original content of file due to limitations but how the content inside those file look i have put below.

file1.json

    {
  "Indicator": {
    "key1": "value 1",
    "key2": "value 2",
    "Name": "value 3",
    "key4": "value 4",
    "Description": "some text",
    "Subformulas": {
      "some key": "some sub-formula"
    },
    "Formula": "some formula"
  }
}

file2.json

    {
  "Indicator": {
    "key1": "value 1",
    "key2": "value 2",
    "key3":"value changed",
    "Name": "value 3",
    "key4": "value 4",
    "Description": "some text",
    "Subformulas": {
      "some key": "change in some sub-formula"
    },
    "Formula": "some formula"
  }
}

I have used this for printing difference in Excel sheet.. code for which I've found on an answer in one of the questions in Stack Overflow, but it is not printing difference into excel sheet...on terminal it is showing difference but in excel sheet it is not. So i think i am doing something wrong and I got no idea how to correct that.

c.items()
c1=list(c.items())
workbook = xlsxwriter.Workbook('myfile.xlsx')
worksheet = workbook.add_worksheet()
row = 0
col = 0

order=sorted(c.keys())

for key in order:
    row  = 1
    #print(key)
    worksheet.write(row,    col,     key)
    for item in c[key]:
        #print(item,row, col 1)
        worksheet.write(row, col   1, item)
        col  = 1
    col = 0

workbook.close()

CodePudding user response:

If you read the source code of jsondiff enter image description here

The 'delete 'row looks odd with the deleted key showing up in the 'New Value' column, but that's the way jsondiff produces its output for explicit syntax. You can of course process it differently.

CodePudding user response:

def diff(a, b):
   result = []
   
   for key in a:
      if key not in b:
         result.append(f'{dict({key: a[key]})} -> {"key deleted"}')
       elif key in b and a[key] != b[key]:
         result.append(f'{dict({key: a[key]})} -> {dict({key: b[key]})}')
   return result
  • Related