Python中高效的json對(duì)比庫deepdiff詳解
工作中我們經(jīng)常要兩段代碼的區(qū)別,或者需要查看接口返回的字段與預(yù)期是否一致,如何快速定位出兩者的差異?除了一些對(duì)比的工具比如Beyond Compare、WinMerge等,或者命令工具diff(在linux環(huán)境下使用),其實(shí)Python中也提供了很多實(shí)現(xiàn)對(duì)比的庫,比如deepdiff和difflib,這兩個(gè)的區(qū)別是deepdiff顯示的對(duì)比效果比較簡(jiǎn)潔,但是可以設(shè)置忽略的字段,difflib顯示的對(duì)比結(jié)果可以是html的,比較詳細(xì)。今天我們就學(xué)習(xí)一下快速實(shí)現(xiàn)代碼和文件對(duì)比的庫–deepdiff。
deepdiff是什么
deepdiff模塊常用來校驗(yàn)兩個(gè)對(duì)象是否一致,包含3個(gè)常用類,DeepDiff,DeepSearch和DeepHash,其中DeepDiff最常用,可以對(duì)字典,可迭代對(duì)象,字符串等進(jìn)行對(duì)比,使用遞歸地查找所有差異。當(dāng)然,也可以可以用來校驗(yàn)多種文件內(nèi)容的差異,如txt、json、圖片等…
https://github.com/seperman/deepdiff
deepdiff安裝
pip install deepdiff
如果實(shí)際請(qǐng)求結(jié)果和預(yù)期值的json數(shù)據(jù)都一致,那么會(huì)返回{}空字典,否則會(huì)返回對(duì)比差異的結(jié)果,接口測(cè)試中我們也可以根據(jù)這個(gè)特點(diǎn)進(jìn)行斷言。
導(dǎo)入
>>> 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
如果對(duì)比結(jié)果不同,將會(huì)給出下面對(duì)應(yīng)的返回:
- 1、type_changes:類型改變的key
- 2、values_changed:值發(fā)生變化的key
- 3、dictionary_item_added:字典key添加
- 4、dictionary_item_removed:字段key刪除
案例1、對(duì)比txt文件
from deepdiff import DeepDiff
"""
a.txt的內(nèi)容是: abc
b.txt的內(nèi)容是: abcd
"""
f1, f2 = open('a.txt', 'r', encoding='utf-8').read(), open('b.txt', 'r', encoding='utf-8').read()
print(DeepDiff(f1, f2))
# 輸出結(jié)果,內(nèi)容值發(fā)生變化 {'values_changed': {'root': {'new_value': 'abcd', 'old_value': 'abc'}}}案例2、對(duì)比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))
# 輸出結(jié)果,id移除,total值發(fā)生改變
#{'dictionary_item_removed': [root['data']['id']], 'values_changed': {"root['data']['total']": {'new_value': 29, 'old_value': 28}}}DeepDiff在單元測(cè)試中的應(yīng)用
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()
測(cè)試用例1實(shí)際返回和預(yù)期結(jié)果json完全一樣,輸出結(jié)果為:{},即兩者沒有差異。
測(cè)試用例2斷言返回author與期望值,值發(fā)生變化。
其實(shí),在實(shí)際接口斷言中,可能需要校驗(yàn)的字段順序不一樣,又或者有一些字段值不需要,為了解決這類問題,Deepdiff也提供了相信的參數(shù),只需要在比較的時(shí)候加入,傳入對(duì)應(yīng)參數(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ù)使用可以,進(jìn)入源碼中查看:

更多關(guān)于DeepDiff的使用可以查看下面的文檔:
https://zepworks.com/deepdiff/5.8.2/diff.html
https://zepworks.com/deepdiff/5.8.2/
https://zepworks.com/tags/deepdiff/
到此這篇關(guān)于Python中高效的json對(duì)比庫deepdiff詳解的文章就介紹到這了,更多相關(guān)Python json對(duì)比庫deepdiff內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解如何使用Pandas處理時(shí)間序列數(shù)據(jù)
時(shí)間序列數(shù)據(jù)在數(shù)據(jù)分析建模中很常見,例如天氣預(yù)報(bào),空氣狀態(tài)監(jiān)測(cè),股票交易等金融場(chǎng)景,本文給大家詳細(xì)介紹了如何使用Pandas處理時(shí)間序列數(shù)據(jù),文中通過代碼示例講解的非常詳細(xì),需要的朋友可以參考下2024-01-01
Python提取Linux內(nèi)核源代碼的目錄結(jié)構(gòu)實(shí)現(xiàn)方法
下面小編就為大家?guī)硪黄狿ython提取Linux內(nèi)核源代碼的目錄結(jié)構(gòu)實(shí)現(xiàn)方法。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-06-06
Python實(shí)現(xiàn)簡(jiǎn)單的HttpServer服務(wù)器示例
本篇文章主要介紹了Python實(shí)現(xiàn)簡(jiǎn)單的HttpServer服務(wù)器示例,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2017-09-09
從源碼解析Python的Flask框架中request對(duì)象的用法
Flask中的request對(duì)象發(fā)送請(qǐng)求使用起來十分方便,但也有一些需要注意的地方,這里我們來從源碼解析Python的Flask框架中request對(duì)象的用法,需要的朋友可以參考下.2016-06-06
Python+matplotlib實(shí)現(xiàn)計(jì)算兩個(gè)信號(hào)的交叉譜密度實(shí)例
這篇文章主要介紹了Python+matplotlib實(shí)現(xiàn)計(jì)算兩個(gè)信號(hào)的交叉譜密度實(shí)例,具有一定借鑒價(jià)值,需要的朋友可以參考下2018-01-01

