1

1st JSON


{
    "x": 10.1,
    "y": 20,
    "name": "Anu",
    "dob": "2010-10-10"
}

2nd JSON

{
    "x": 10,
    "y": 20,
    "name": "Ani",
    "dob": "2010-10-11",
    ā€œzā€:100
}

Result JSON

{
    "x": 0.1,
    "name": "Text change",
    "dob": "1"
    "z": "Only in 2"
}

So i tried converting the json strings to dictionary using the json.loads function and then getting the difference between the dictionaries using deepdiff but it gives me the output that what has changed in the dictionary and not the desired output as mentioned above.

SimonUnderwood
  • 469
  • 3
  • 12
  • You would need a special set of rules that somehow determines what the data types (the values) are and how to interpret their differences. e.g., we see that the 'dob' value is a string representation of a date. But it's just a string. How would you know which values have to be converted to date objects? Why "only in 2"? That's just bizarre – DarkKnight Apr 05 '23 at 18:04
  • Only in 2 means that the key was only found in the 2nd dictionary. – user662650 Apr 06 '23 at 04:56

1 Answers1

0

This would be one way to do it

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)
user662650
  • 176
  • 1
  • 12