您可以使用Python中的json和difflib模块来比较两个JSON文件并显示差异。下面是一个示例代码:
import json
import difflib
def compare_json_files(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
json1 = json.load(f1)
json2 = json.load(f2)
diff = difflib.unified_diff(json.dumps(json1, indent=4).splitlines(),
json.dumps(json2, indent=4).splitlines())
for line in diff:
print(line)
# 例子使用
compare_json_files('file1.json', 'file2.json')
在这个示例中,我们首先使用json.load()
函数加载两个JSON文件,并将它们存储在json1
和json2
变量中。然后,我们使用difflib.unified_diff()
函数比较这两个JSON对象的字符串表示形式的行。最后,我们将差异行打印出来。
请注意,这个示例假设输入的JSON文件是有效的,并且使用相同的键和值类型。如果两个JSON文件的结构不同,那么可能需要进行额外的处理来正确比较它们。