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
Recommended Snippets
Python Remove Duplicates from List of Dicts
Remove duplicates from a list of dictionaries based on a specific key in the dictionaries.
Python
#dict+1
6
0
Python read JSON from file example
The simplest code snippet for reading a JSON file using Python, implemented with the built-in json module.
Python
#json
12
0
Python: Write Dict to CSV with Headers
Write a list of dictionaries to a CSV file and automatically generate headers.
Python
#dict+1
6
0
Comments
Loading...