如何仅比较 json 文件中的键名称

How to compare only key names in a json file

提问人:salosila 提问时间:11/10/2023 更新时间:11/10/2023 访问量:16

问:

我正在开发一个 Python 脚本,该脚本比较两个 JSON 响应(和 )并识别不同的键。该脚本使用递归函数 遍历 JSON 对象的嵌套结构。example_response.jsonactual_response.jsoncompare_json_keys

目标是突出显示任一响应中的任何额外键,并指示发生差异的特定路径。脚本似乎按预期运行,但我收到一条评论,表明我的帖子缺乏足够的细节。

有人可以审查代码并就是否有潜在的改进或我是否可以澄清任何方面提供反馈吗?此外,如果有其他方法可以实现相同的目标,我将不胜感激。

谢谢!

import json
import os

def compare_json_keys(actual_dict, example_dict, current_path=''):
    differing_keys = set(actual_dict.keys()) ^ set(example_dict.keys())
    extra_keys_actual = set(actual_dict.keys()) - set(example_dict.keys())
    extra_keys_example = set(example_dict.keys()) - set(actual_dict.keys())

    # Check for missing keys in one of the dictionaries
    if not differing_keys:
        if extra_keys_actual:
            for key in extra_keys_actual:
                print(f"Actual response has extra key in {current_path}.{key}")
        if extra_keys_example:
            for key in extra_keys_example:
                print(f"Example response has extra key in {current_path}.{key}")

    # Recursive comparison of keys
    for key in set(actual_dict.keys()) & set(example_dict.keys()):
        path = f"{current_path}.{key}" if current_path else key

        if isinstance(actual_dict[key], dict) and isinstance(example_dict[key], dict):
            # Recursive call to compare nested objects
            differing_keys |= compare_json_keys(actual_dict[key], example_dict[key], current_path=path)
        elif isinstance(actual_dict[key], list) and isinstance(example_dict[key], list):
            # Recursive call to compare nested lists
            for i, (item_actual, item_example) in enumerate(zip(actual_dict[key], example_dict[key])):
                differing_keys |= compare_json_keys(item_actual, item_example, current_path=f"{path}[{i}]")
        elif key in extra_keys_actual or key in extra_keys_example:
            differing_keys.add(path)

    return differing_keys


# Get the path to the folder containing the script and JSON files
current_directory = os.path.dirname(os.path.abspath(__file__))

# Form full paths to the JSON files
example_response_path = os.path.join(current_directory, 'example_response.json')
actual_response_path = os.path.join(current_directory, 'actual_response.json')

# Read JSON files and convert them to dictionaries
with open(example_response_path, 'r') as file1, open(actual_response_path, 'r') as file2:
    example_response = json.load(file1)
    actual_response = json.load(file2)

# Compare field names in the responses
differing_keys = compare_json_keys(actual_response, example_response)
if not differing_keys:
    print("Both responses have the same set of fields.")
else:
    print("Differing keys:")
    for key in differing_keys:
        file_origin = 'example' if key in example_response else 'actual'
        print(f"{key} in {file_origin} response")
json python-3.x 比较 响应

评论


答: 暂无答案