MST

星途 面试题库

面试题:Python中如何高效解析多层嵌套JSON数据并提取特定路径的值

给定一个复杂的多层嵌套JSON数据结构,例如包含多级字典和列表的嵌套。要求编写Python代码,能够根据用户指定的路径(如['level1', 'level2', 0, 'target_key']),准确提取出对应路径下的值,并且要考虑路径不存在等异常情况的处理。
33.1万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
def get_value_from_json(json_data, path):
    try:
        for key in path:
            if isinstance(json_data, dict):
                json_data = json_data.get(key)
            elif isinstance(json_data, list) and isinstance(key, int) and key < len(json_data):
                json_data = json_data[key]
            else:
                return None
        return json_data
    except (TypeError, KeyError, IndexError):
        return None


你可以使用以下方式调用:

# 示例用法
json_example = {
    "level1": {
        "level2": [
            {"target_key": "value"}
        ]
    }
}
path_example = ['level1', 'level2', 0, 'target_key']
result = get_value_from_json(json_example, path_example)
print(result)