一般用做接口版本升級后前后返回的數(shù)據(jù)格式是否有誤,或者兩個環(huán)境的接口是否是一致
1、需要安裝diff庫:pip install deepdiff
2、最基本的兩個json比較
from deepdiff import DeepDiff
from pprint import pprint
# t1 = {"one": 1, "two": 2, "three": 3}
# t2 = {"one": 1, "two": 4, "three": "6"}
if __name__ == "__main__":
res = DeepDiff(t1, t2,ignore_order)
pprint(res)
輸出結(jié)果:image.png
通過diff,two的值不一樣篓叶,three的類型不一樣
pprint是輸出格式更完整,標準化
3羞秤、忽略順序或重復項列出差異
from deepdiff import DeepDiff
from pprint import pprint
t1 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 2, 3]}}
t2 = {1:1, 2:2, 3:3, 4:{"a":"hello", "b":[1, 3, 2, 3]}}
if __name__ == "__main__":
res = DeepDiff(t1, t2,ignore_order=True)
# res = DeepDiff(t1, t2)
pprint(res)
運行結(jié)果:image.png
即兩者沒有差異缸托,因為忽略了b列表的順序及重復項
4、從比較中排除對象樹的一部分瘾蛋,如token俐镐、uuid等容易變化的數(shù)
from deepdiff import DeepDiff
from pprint import pprint
t1 = {"for life": "vegan", "ingredients": ["no meat", "no eggs", "no dairy"]}
t2 = {"for life": "vegan", "ingredients": ["veggies", "tofu", "soy sauce"]}
if __name__ == "__main__":
res = DeepDiff(t1, t2,exclude_paths={"root['ingredients']"})
pprint(res)
運行結(jié)果:{},表示忽略了ingredients的對比
https://github.com/seperman/deepdiff
https://pypi.org/project/deepdiff/