You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DeepDiff对比多键嵌套JSON时未拆分增删改差异,如何实现精准拆分?

DeepDiff对比多键嵌套JSON时未拆分增删改差异,如何实现精准拆分?

哈哈,这个坑我踩过!你遇到的是DeepDiff默认的「差异分组」机制在搞事情~

问题原因

DeepDiff默认有个cutoff_distance_for_pairs参数(默认值是0.3),它的作用是:当两个子字典的差异键数量占总键数的比例超过这个阈值时,DeepDiff会“偷懒”把整个子字典标记为「值变化」,而不是逐个拆分出新增、删除、修改的具体键。

你第二个例子里,height子字典的差异比例已经超过了0.3(原本3个键,现在换了2个,还改了1个值),所以触发了合并分组,导致你看不到单独的增删项。

解决方案

初始化DeepDiff时,把cutoff_distance_for_pairs设为1.0,就能强制它不管差异比例多少,都逐个拆分每个键的变化:

expected  = {"name":"Cake","image":{"width":200,"height":{"cm":200,"inch":15,"mile":20}}}
actual = {"name":"Cake","image":{"width":250,"height":{"cm":290,"foot":10,"yard":90}}}
# 关键:添加 cutoff_distance_for_pairs=1.0 参数
ddiff = DeepDiff(expected, actual, cutoff_distance_for_pairs=1.0)
print(ddiff, '\n\n')

预期输出

这样运行后,就能得到你想要的精准拆分结果:

{'dictionary_item_added': ["root['image']['height']['foot']", "root['image']['height']['yard']"], 'dictionary_item_removed': ["root['image']['height']['inch']", "root['image']['height']['mile']"], 'values_changed': {"root['image']['width']": {'new_value': 250, 'old_value': 200}, "root['image']['height']['cm']": {'new_value': 290, 'old_value': 200}}} 

如果这个参数还不够,你可以再加上strict_checking=True(不过一般cutoff_distance_for_pairs=1.0就足够解决问题了)。

备注:内容来源于stack exchange,提问作者anon-explorer

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.14 13:42:59