LoginSignup
1
0

More than 1 year has passed since last update.

json の差分比較

Posted at
import json
from jsondiff import diff

# 比較するJSONファイルのパス
file1_path = "/path/to/file1.json"
file2_path = "/path/to/file2.json"

# JSONファイルの読み込み
with open(file1_path) as f:
    file1 = json.load(f)
with open(file2_path) as f:
    file2 = json.load(f)

# JSONファイルの差分を計算
result = diff(file1, file2)

# ファイル1にしか存在しない要素を出力
file1_only = []
for k in result.keys():
    if k.startswith("-"):
        file1_only.append(result[k])
with open("file1_only.json", "w") as f:
    json.dump(file1_only, f, indent=2)

# ファイル2にしか存在しない要素を出力
file2_only = []
for k in result.keys():
    if k.startswith("+"):
        file2_only.append(result[k])
with open("file2_only.json", "w") as f:
    json.dump(file2_only, f, indent=2)

# 両方のファイルに存在するが、値が異なる要素を出力
different_values = []
for k in result.keys():
    if k.startswith("~"):
        different_values.append(result[k])
with open("different_values.json", "w") as f:
    json.dump(different_values, f, indent=2)

1
0
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
1
0