Ale*_*huk 3 c++ python deep-diff
DeepDiff 结果如下所示:
{'dictionary_item_added': [root[5], root[6]], 'dictionary_item_removed': [root[4]]}
Run Code Online (Sandbox Code Playgroud)
对于对更改的人工审查,这仅适用于小示例。我需要类似 GitHub 提交和拉取请求中显示的代码文件差异,但对于 json。
所以这是我的问题:
与代码不同,json 不关心格式,也不关心字典中键的顺序。
我可以通过预先排序 json 中的所有字典然后将它们与 git-diff 进行比较来避免不使用 DeepDiff。然而,将文件写入磁盘并取出git-diff是很混乱的。只是在做DeepDiff(t1, t2)就很干净。
我正在看的例子是:
{'dictionary_item_added': [root[5], root[6]], 'dictionary_item_removed': [root[4]]}
Run Code Online (Sandbox Code Playgroud)
我希望看到已更改的值中突出显示的单词,如下所示:
difflib 的 ndiff可能是您想要实现的目标:
import difflib
import json
from typing import Callable
t1 = {1:1, 3:3, 4:4}
t2 = {1:1, 3:3, 5:5, 6:6}
RED: Callable[[str], str] = lambda text: f"\u001b[31m{text}\033\u001b[0m"
GREEN: Callable[[str], str] = lambda text: f"\u001b[32m{text}\033\u001b[0m"
def get_edits_string(old: str, new: str) -> str:
result = ""
lines = difflib.ndiff(old.splitlines(keepends=True), new.splitlines(keepends=True))
for line in lines:
line = line.rstrip()
if line.startswith("+"):
result += GREEN(line) + "\n"
elif line.startswith("-"):
result += RED(line) + "\n"
elif line.startswith("?"):
continue
else:
result += line + "\n"
return result
print(
get_edits_string(
json.dumps(t1, indent=4, sort_keys=True),
json.dumps(t2, indent=4, sort_keys=True)
)
)
Run Code Online (Sandbox Code Playgroud)
这样做的好处对于 CLI 来说也很有帮助——我已经在代码中过滤了它,但它也有无色差异,并标记了?更改的位置。
| 归档时间: |
|
| 查看次数: |
2809 次 |
| 最近记录: |