Python compare two json file and get only the difference

11,362

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(("- ", "+ "))]
Share:
11,362

Related videos on Youtube

locklockM
Author by

locklockM

Updated on June 04, 2022

Comments

  • locklockM
    locklockM almost 2 years

    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

  • locklockM
    locklockM over 5 years
    yes, but 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.
  • julienc
    julienc over 5 years
    @locklockM You should update your question with this new information for other users to understand what you would like to achieve. Give an example with input files and expected output.
  • julienc
    julienc over 5 years
    I guess text comparison could still be applied if you're using some kind of "prettifying" on your input, something like json.dumps(..., sort_keys=True, indent=4). But I agree with you that unsererialized comparison is probably the best option. I just assumed from OP's question that their data was already formatted in a way that would work with text comparison.
  • bruno desthuilliers
    bruno desthuilliers over 5 years
    @julienc didn't think of this actually. You should edit your answer to clarify those assumptions, really.