使用Python编写脚本来比较JSON文件的键值。
示例代码如下:
import json
def compare_json(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
first_json = json.load(f1)
second_json = json.load(f2)
diff_keys = set(first_json.keys()) ^ set(second_json.keys())
common_keys = set(first_json.keys()) & set(second_json.keys())
for key in common_keys:
if(first_json[key] != second_json[key]):
print("Values are different for key: {}".format(key))
print("Keys only in {} : {}".format(file1, set(first_json.keys()) - set(second_json.keys())))
print("Keys only in {} : {}".format(file2, set(second_json.keys()) - set(first_json.keys())))
使用方法:
compare_json('file1.json', 'file2.json')
该脚本将会返回两个JSON文件中不同的键值,以及仅在一个文件中出现的键。