Python でネストされた JSON ファイルを読み込む例

言語:
Python
8 閲覧
0 お気に入り
3時間前

コード実装

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を回避します

コメント

読み込み中...