Python常见Json对比库deepdiff、json_tools、jsonpatch
对比两个json对象差异,常见的第三方对比库deepdiff、json_tools、jsonpatch都能够满足我们的需求。
用法:
deepdiff
from deepdiff import DeepDiff
a = {"name": "yanan", "pro": {"sh": "shandong", "city": ["zibo", "weifang"]}}
b = {"name": "Yanan", "pro": {"sh": "shandong", "town": ["taian", "weifang"]}}
result = DeepDiff(a, b)
print(result)
输出结果:
{'dictionary_item_added': [root['pro']['town']], 'dictionary_item_removed': [root['pro']['city']], 'values_changed': {"root['name']": {'new_value': 'Yanan', 'old_value': 'yanan'}}}
json_tools
import json_tools
a = {"name": "yanan", "pro": {"sh": "shandong", "city": ["zibo", "weifang"]}}
b = {"name": "Yanan", "pro": {"sh": "shandong", "town": ["taian", "weifang"]}}
result = json_tools.diff(a, b)
print(result)
输出结果:
[{'replace': '/name', 'value': 'Yanan', 'prev': 'yanan'}, {'remove': '/pro/city', 'prev': ['zibo', 'weifang']}, {'add': '/pro/town', 'value': ['taian', 'weifang']}]
jsonpatch
import jsonpatch
a = {"name": "yanan", "pro": {"sh": "shandong", "city": ["zibo", "weifang"]}}
b = {"name": "Yanan", "pro": {"sh": "shandong", "town": ["taian", "weifang"]}}
result = jsonpatch.JsonPatch.from_diff(a, b)
print(result)
输出结果:
[{"op": "remove", "path": "/pro/city"}, {"op": "add", "path": "/pro/town", "value": ["taian", "weifang"]}, {"op": "replace", "path": "/name", "value": "Yanan"}]
但无论哪种方法,都不方便我们根据对比结果,进行修改原始数据。
最后感谢每一个认真阅读我文章的人,礼尚往来总是要有的,虽然不是什么很值钱的东西,如果你用得到的话可以直接拿走:【文末自行领取】
这些资料,对于【软件测试】的朋友来说应该是最全面最完整的备战仓库,这个仓库也陪伴上万个测试工程师们走过最艰难的路程,希望也能帮助到你!