Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python compare two json file and get only the difference

I want to compare two json file and get only the difference between them.

I have a code that can compare two json file, but he get me the line which is the same, and I want only the difference.

+     "AAAA": {
+       "name": "toto",
+       "age": null
+     },
      "BBBB": {
        "name": "tete",
        "age": 26
      },
-     "CCCC": {
?               ^ ^ ^^^
+     "DDDD": {
?               ^ ^ ^^^
-       "name": "tete",
?                   ^^^      ^
+       "age": "45",


with open('orig.json') as orig_file, open('target.json') as target_file:
    diff = difflib.Differ()
    result = diff.compare(target_file.readlines(),    orig_file.readlines())
    print("### JSON DIFF ###")
    print(''.join(result))

I don't want to keep if the key value is the same, but if the key value is differente, I want to keep the key.

FOr instance I don't want to keep "BBBB" key, beacause it is the same between two files, and other key I want to keep because, value is differente

like image 699
locklockM Avatar asked May 13 '26 05:05

locklockM


1 Answers

According to the documentation:

Each line of a Differ delta begins with a two-letter code:

| Code | Meaning                                   |
|------|-------------------------------------------|
| '- ' | line unique to sequence 1                 |
| '+ ' | line unique to sequence 2                 |
| '  ' | line common to both sequences             |
| '? ' | line not present in either input sequence |

So basically, all you have to do is filter lines starting with either "- " or "+ ".

result = diff.compare(target_file.readlines(), orig_file.readlines())
result = [line for line in result if line.startswith(("- ", "+ "))]
like image 177
julienc Avatar answered May 14 '26 19:05

julienc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!