Python中高效的json對比庫deepdiff詳解
工作中我們經常要兩段代碼的區(qū)別,或者需要查看接口返回的字段與預期是否一致,如何快速定位出兩者的差異?除了一些對比的工具比如Beyond Compare、WinMerge等,或者命令工具diff(在linux環(huán)境下使用),其實Python中也提供了很多實現(xiàn)對比的庫,比如deepdiff和difflib,這兩個的區(qū)別是deepdiff顯示的對比效果比較簡潔,但是可以設置忽略的字段,difflib顯示的對比結果可以是html的,比較詳細。今天我們就學習一下快速實現(xiàn)代碼和文件對比的庫–deepdiff。
deepdiff是什么
deepdiff模塊常用來校驗兩個對象是否一致,包含3個常用類,DeepDiff,DeepSearch和DeepHash,其中DeepDiff最常用,可以對字典,可迭代對象,字符串等進行對比,使用遞歸地查找所有差異。當然,也可以可以用來校驗多種文件內容的差異,如txt、json、圖片等…
https://github.com/seperman/deepdiff
deepdiff安裝
pip install deepdiff
如果實際請求結果和預期值的json數(shù)據(jù)都一致,那么會返回{}空字典,否則會返回對比差異的結果,接口測試中我們也可以根據(jù)這個特點進行斷言。
導入
>>> from deepdiff import DeepDiff # For Deep Difference of 2 objects >>> from deepdiff import grep, DeepSearch # For finding if item exists in an object >>> from deepdiff import DeepHash # For hashing objects based on their contents
如果對比結果不同,將會給出下面對應的返回:
- 1、type_changes:類型改變的key
- 2、values_changed:值發(fā)生變化的key
- 3、dictionary_item_added:字典key添加
- 4、dictionary_item_removed:字段key刪除
案例1、對比txt文件
from deepdiff import DeepDiff
"""
a.txt的內容是: abc
b.txt的內容是: abcd
"""
f1, f2 = open('a.txt', 'r', encoding='utf-8').read(), open('b.txt', 'r', encoding='utf-8').read()
print(DeepDiff(f1, f2))
# 輸出結果,內容值發(fā)生變化 {'values_changed': {'root': {'new_value': 'abcd', 'old_value': 'abc'}}}案例2、對比json
?
from deepdiff import DeepDiff
?
json1={
'code': 0,
"message": "成功",
"data": {
"total": 28,
"id":123
}
}
json2={
'code':0,
"message":"成功",
"data": {
"total": 29,
}
}
print(DeepDiff(json1,json2))
# 輸出結果,id移除,total值發(fā)生改變
#{'dictionary_item_removed': [root['data']['id']], 'values_changed': {"root['data']['total']": {'new_value': 29, 'old_value': 28}}}DeepDiff在單元測試中的應用
import unittest
import requests
from deepdiff import DeepDiff
class MyCase(unittest.TestCase):
expect = {
'slideshow': {
'author': 'Yours Truly',
'date': 'date of publication',
'slides': [{
'title': 'Wake up to WonderWidgets!',
'type': 'all'
}, {
'items': ['Why <em>WonderWidgets</em> are great', 'Who <em>buys</em> WonderWidgets'],
'title': 'Overview',
'type': 'all'
}],
'title': 'Sample Slide Show'
}
}
?
def setUp(self):
self.response = requests.get('http://www.httpbin.org/json').json()
print(self.response)
?
def test_case_01(self):
print(DeepDiff(self.response, self.expect))
?
def test_case_02(self):
print(DeepDiff(self.response['slideshow']['author'], 'Yours Truly1'))
?
if __name__ == '__main__':
unittest.main()
測試用例1實際返回和預期結果json完全一樣,輸出結果為:{},即兩者沒有差異。
測試用例2斷言返回author與期望值,值發(fā)生變化。
其實,在實際接口斷言中,可能需要校驗的字段順序不一樣,又或者有一些字段值不需要,為了解決這類問題,Deepdiff也提供了相信的參數(shù),只需要在比較的時候加入,傳入對應參數(shù)即可。
ignore order(忽略排序)ignore string case(忽略大小寫)exclude_paths排除指定的字段
print(DeepDiff(self.response, self.expect,view='tree',ignore_order=True,ignore_string_case=True,exclude_paths={"root['slideshow']['date']"}))更多的參數(shù)使用可以,進入源碼中查看:

更多關于DeepDiff的使用可以查看下面的文檔:
https://zepworks.com/deepdiff/5.8.2/diff.html
https://zepworks.com/deepdiff/5.8.2/
https://zepworks.com/tags/deepdiff/
到此這篇關于Python中高效的json對比庫deepdiff詳解的文章就介紹到這了,更多相關Python json對比庫deepdiff內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python提取Linux內核源代碼的目錄結構實現(xiàn)方法
下面小編就為大家?guī)硪黄狿ython提取Linux內核源代碼的目錄結構實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-06-06
Python實現(xiàn)簡單的HttpServer服務器示例
本篇文章主要介紹了Python實現(xiàn)簡單的HttpServer服務器示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
從源碼解析Python的Flask框架中request對象的用法
Flask中的request對象發(fā)送請求使用起來十分方便,但也有一些需要注意的地方,這里我們來從源碼解析Python的Flask框架中request對象的用法,需要的朋友可以參考下.2016-06-06
Python+matplotlib實現(xiàn)計算兩個信號的交叉譜密度實例
這篇文章主要介紹了Python+matplotlib實現(xiàn)計算兩個信號的交叉譜密度實例,具有一定借鑒價值,需要的朋友可以參考下2018-01-01

