Python Read Nested JSON File Example

Language:
Python
8 views
0 favorites
1 hours ago

Code Implementation

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"

How to read JSON files with nested structures in Python and safely access deep-level fields.

#json#nested

Snippet Description

  • Replace data.json with the path to your JSON file
  • The keys parameter is a list representing the fields to access layer by layer
  • If a field does not exist, {} will be returned to avoid KeyError

Comments

Loading...