코드 구현
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를 방지합니다
추천 스니펫
댓글
로딩 중...