Python 读取嵌套 JSON 文件示例

语言:
Python
8 浏览
0 收藏
2小时前

代码实现

Python
import json

def read_nested_json(file_path, keys):
    """
    Read a nested JSON file and access deep fields via keys
    :param file_path: JSON file path
    :param keys: List of fields to access
    """
    with open(file_path, "r", encoding="utf-8") as f:
        data = json.load(f)

    result = data
    for key in keys:
        result = result.get(key, {})
    return result

# Example Usage
# Assuming JSON: {"user": {"profile": {"name": "Alice"}}}
value = read_nested_json("data.json", ["user", "profile", "name"])
print(value)  # Output "Alice"

如何在 Python 中读取带有嵌套结构的 JSON 文件,并安全访问深层字段。

#json#嵌套

片段说明

  • data.json 替换为你的 JSON 文件路径
  • keys 参数是一个列表,表示要逐层访问的字段
  • 如果某个字段不存在,会返回 {},避免 KeyError

评论

加载中...