PUROGU LADESU

ポエムがメインのブログです。

【Python】JSONの要素の実際と期待値の差異を取得する

jsonを並び替える。
片方にしか存在しないオブジェクトを返す。
まあ並び替えなくてもいいんだけど。

with open("actual.json") as f:
    act = json.load(f)
    
with open("expected.json") as f:
    exp = json.load(f)

# 並び替えたい場合
act.sort(key=operator.itemgetter("Name", "Age", "Birthday"))
exp.sort(key=operator.itemgetter("Name", "Age", "Birthday"))
# exp.sort(key=lambda x: (x["Name"], x["Age"]))

# print(json.dumps(act))
# print(json.dumps(exp))

print("only in act. something is missing in expected.json ")
print([x for x in act if x not in exp])
# for x in act:
#     if x not in exp:
#         print(x)

print("only in exp. too much items in expected.json")
print([x for x in exp if x not in act])
# for x in exp:
#     if x not in act:
#         print(x)


actual.json

[
  {
    "Name": "Bob",
    "Age": 30,
    "Birthday": "1994-08-20"
  },
  {
    "Name": "Alice",
    "Age": 25,
    "Birthday": "1999-05-15"
  },
  {
    "Name": "David",
    "Age": 35,
    "Birthday": "1989-03-25"
  },
  {
    "Name": "Eve",
    "Age": 28,
    "Birthday": "1996-11-05"
  }
]

expected.json

[
  {
    "Name": "Alice",
    "Age": 25,
    "Birthday": "1999-05-15"
  },
  {
    "Name": "Bob",
    "Age": 30,
    "Birthday": "1994-08-20"
  },
  {
    "Name": "Charlie",
    "Age": 40,
    "Birthday": "1984-12-10"
  },
  {
    "Name": "David",
    "Age": 35,
    "Birthday": "1989-03-25"
  },
  {
    "Name": "Eve",
    "Age": 28,
    "Birthday": "1996-11-05"
  }
]