带正则表达式的DeepDiff忽略

2024-05-28 23:21:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个目标:

d1 = [ { "id": 3, "name": "test", "components": [ { "id": 1, "name": "test" }, { "id": 2, "name": "test2" } ] } ]
d2 = [ { "id": 4, "name": "test", "components": [ { "id": 2, "name": "test" }, { "id": 3, "name": "test"2 } ] } ]

如您所见,所有内容都保持不变,但根对象上的id属性以及components内部的id属性都发生了更改

我正在使用DeepDiff来比较d1d2,并试图忽略id对象的比较。然而,我不知道如何实现这一点。我尝试了以下方法,但似乎不起作用

excluded_paths = "root[\d+\]['id']"
diff = DeepDiff(d1, d2, exclude_paths=excluded_paths)

Tags: 对象方法nametestid内容目标属性
1条回答
网友
1楼 · 发布于 2024-05-28 23:21:51

您可以尝试使用exclude_obj_callback

from deepdiff import DeepDiff

def exclude_obj_callback(obj, path):
    return True if "id" in path else False

d1 = [ { "id": 3, "name": "test", "components": [ { "id": 1, "name": "test" }, { "id": 2, "name": "test2" } ] } ]
d2 = [ { "id": 4, "name": "test", "components": [ { "id": 2, "name": "test" }, { "id": 3, "name": "test2" } ] } ]
print(DeepDiff(d1, d2, exclude_obj_callback=exclude_obj_callback))

这将为每个包含字符串“id”的深层组件返回一个布尔值。您可能需要注意这一点,因为您可能会排除其他您不想排除的对象。解决这个问题的一种方法是设置不太通用的键值,例如“component_id”

相关问题 更多 >

    热门问题