LoginSignup
2
3

More than 1 year has passed since last update.

PythonでJsonの差分を確認する(備忘録

Last updated at Posted at 2022-09-25
前置き
使用したのは標準ライブラリのdifflib。

2つのJsonファイルの差分を確認するPythonを作成しました。

微量な差分であれば今回のPythonは使えるかもしれません。
よって使う状況に応じ、差分を確認しやすいようどうぞご自身でPythonを書き換え下さい。

今回は自分への備忘録として。またこれがどなたかの参考に少しでもなれば幸いです。
長い前置きもここらで。
では。


差分を確認するJson
sample1.json
{
    "Sample": {
        "Sample_A": [0, 1, 2],
        "Sample_B": {
            "a": 1,
            "b": 2,
            "c": 3,
            "d": ["a", "b", "c"]
        },
        "Sample_C": "HogeHoge"
    }
}
sample2.json
{
    "Sample": {
        "Sample_A": [0, 1, 0],
        "Sample_B": {
            "a": 1,
            "b": 2,
            "c": 3,
            "d": ["a", "b", "ccc"]
        },
        "Sample_C": "Hoge"
    }
}

差分を確認するPython
check_diff.py
import sys
import json
import difflib
import pprint as pp

#JsonファイルをList型に変換する
def conv_json_to_list(src_json):
    #まずjsonファイルを読み込み、dict変換
    with open(src_json, "r") as f:
        src_to_dict = json.load(f)
    
    #pprint.pformatによって dict型 -> String型 に変換
    #sort_dicts = False にすることで、pprintによるformat後も、既存の辞書の順番を維持する。
    src_to_str = pp.pformat(src_to_dict, sort_dicts = False)
    #改行を区切りに String型 -> List型 に変換する
    src_to_list = src_to_str.split("\n")
    return src_to_list

#2つのJsonの差異を確認し、標準出力
def display_difference(src_json1, src_json2):
    #2つのJsonをList化し、差分を確認。
    diff_result = difflib.ndiff(conv_json_to_list(src_json1), conv_json_to_list(src_json2))
    #差異を標準出力
    for line in diff_result:
        if line[0:1] == "-":
            print("Src1: " + line)
        elif line[0:1] == "+":
            print("Src2: " + line)
        elif line[0:1] == "?":
            print("Diff: " + line)

if __name__ == "__main__":
    src_json1 = sys.argv[1]
    src_json2 = sys.argv[2]
    display_difference(src_json1, src_json2)


実行結果

$ python check_diff.py sample1.json sample2.json

Src1: - {'Sample': {'Sample_A': [0, 1, 2],
Diff: ?                                ^

Src2: + {'Sample': {'Sample_A': [0, 1, 0],
Diff: ?                                ^

Src1: -             'Sample_B': {'a': 1, 'b': 2, 'c': 3, 'd': ['a', 'b', 'c']},
Src2: +             'Sample_B': {'a': 1, 'b': 2, 'c': 3, 'd': ['a', 'b', 'ccc']},
Diff: ?                                                                   ++

Src1: -             'Sample_C': 'HogeHoge'}}
Diff: ?                          ----

Src2: +             'Sample_C': 'Hoge'}}

このように差分があるところが「^, -, +」等で表記されます。

詳しくは公式Documentをご参考ください↓
https://docs.python.org/3/library/difflib.html

以上でした〜!

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3