소개
중첩된 Python JSON 객체에서 데이터를 탐색하고 추출하는 것은 데이터 처리에서 흔히 사용되는 작업입니다. API, 구성 파일 또는 데이터 저장소 작업을 하든, 복잡한 JSON 구조에서 값을 효율적으로 추출하는 방법을 이해하는 것은 모든 Python 개발자에게 필수적입니다.
이 Lab 에서는 Python 을 사용하여 중첩된 JSON 객체에서 값을 추출하는 실용적인 기술을 배우게 됩니다. 기본적인 인덱싱부터 누락된 키를 우아하게 처리하는 보다 강력한 방법까지 다양한 접근 방식을 탐구할 것입니다. 이 Lab 을 마치면 Python 프로젝트에서 중첩된 JSON 데이터를 처리하기 위한 모범 사례에 대한 실질적인 경험을 얻게 될 것입니다.
중첩된 JSON 객체 생성 및 이해
JSON (JavaScript Object Notation) 은 사람이 읽기 쉽고 기계가 쉽게 구문 분석할 수 있는 가벼운 데이터 교환 형식입니다. Python 에서 JSON 데이터는 일반적으로 딕셔너리와 리스트로 표현됩니다.
이 Lab 전체에서 사용할 샘플 중첩 JSON 객체를 생성하는 것으로 시작해 보겠습니다.
샘플 JSON 파일 생성
WebIDE 인터페이스를 열고
/home/labex/project디렉토리에sample.json이라는 새 파일을 만듭니다.다음 JSON 내용을 파일에 복사합니다.
{
"person": {
"name": "John Doe",
"age": 35,
"contact": {
"email": "john.doe@example.com",
"phone": "555-123-4567"
},
"address": {
"street": "123 Main St",
"city": "Anytown",
"state": "CA",
"zip": "12345"
},
"hobbies": ["reading", "hiking", "photography"],
"employment": {
"company": "Tech Solutions Inc.",
"position": "Software Developer",
"years": 5,
"projects": [
{
"name": "Project Alpha",
"status": "completed"
},
{
"name": "Project Beta",
"status": "in-progress"
}
]
}
}
}
- 파일을 저장합니다.
JSON 구조 이해
이 JSON 객체는 다양한 속성을 가진 사람을 나타냅니다. 구조는 다음과 같습니다.
- 간단한 키 - 값 쌍 (name, age)
- 중첩된 객체 (contact, address, employment)
- 배열 (hobbies)
- 객체 배열 (projects)
JSON 데이터의 구조를 이해하는 것은 데이터에서 값을 효과적으로 추출하는 첫 번째 단계입니다. 이 구조를 시각화해 보겠습니다.
person
├── name
├── age
├── contact
│ ├── email
│ └── phone
├── address
│ ├── street
│ ├── city
│ ├── state
│ └── zip
├── hobbies [array]
└── employment
├── company
├── position
├── years
└── projects [array of objects]
├── name
└── status
Python 에서 JSON 로드
이제 이 JSON 파일을 로드하는 Python 스크립트를 만들어 보겠습니다. 동일한 디렉토리에 json_basics.py라는 새 파일을 만듭니다.
import json
## Load JSON from file
with open('sample.json', 'r') as file:
data = json.load(file)
## Verify data loaded successfully
print("JSON data loaded successfully!")
print(f"Type of data: {type(data)}")
print(f"Keys at the top level: {list(data.keys())}")
print(f"Keys in the person object: {list(data['person'].keys())}")
다음 명령으로 스크립트를 실행합니다.
python3 json_basics.py
다음과 유사한 출력을 볼 수 있습니다.
JSON data loaded successfully!
Type of data: <class 'dict'>
Keys at the top level: ['person']
Keys in the person object: ['name', 'age', 'contact', 'address', 'hobbies', 'employment']
이것은 JSON 파일이 Python 딕셔너리로 올바르게 로드되었음을 확인합니다. 다음 단계에서는 이 중첩된 구조에서 값을 추출하는 다양한 방법을 살펴보겠습니다.
JSON 데이터 접근을 위한 기본 방법
이제 JSON 데이터를 로드했으므로 중첩된 JSON 객체에서 값에 접근하기 위한 기본 방법을 살펴보겠습니다.
대괄호를 사용한 직접 인덱싱
중첩된 JSON 객체에서 값에 접근하는 가장 간단한 방법은 적절한 키와 함께 대괄호를 사용하는 것입니다. direct_access.py라는 새 파일을 만들어 보겠습니다.
import json
## Load JSON from file
with open('sample.json', 'r') as file:
data = json.load(file)
## Access simple values
name = data["person"]["name"]
age = data["person"]["age"]
print(f"Name: {name}, Age: {age}")
## Access nested values
email = data["person"]["contact"]["email"]
city = data["person"]["address"]["city"]
print(f"Email: {email}, City: {city}")
## Access array values
first_hobby = data["person"]["hobbies"][0]
all_hobbies = data["person"]["hobbies"]
print(f"First hobby: {first_hobby}")
print(f"All hobbies: {all_hobbies}")
## Access values in arrays of objects
first_project_name = data["person"]["employment"]["projects"][0]["name"]
first_project_status = data["person"]["employment"]["projects"][0]["status"]
print(f"First project: {first_project_name}, Status: {first_project_status}")
스크립트를 실행합니다.
python3 direct_access.py
다음과 유사한 출력을 볼 수 있습니다.
Name: John Doe, Age: 35
Email: john.doe@example.com, City: Anytown
First hobby: reading
All hobbies: ['reading', 'hiking', 'photography']
First project: Project Alpha, Status: completed
직접 인덱싱의 문제점
직접 인덱싱은 JSON 데이터의 정확한 구조를 알고 모든 키가 존재한다고 확신하는 경우 잘 작동합니다. 그러나 키가 누락된 경우 KeyError 예외가 발생합니다.
error_demo.py라는 파일을 만들어 이 문제를 시연해 보겠습니다.
import json
## Load JSON from file
with open('sample.json', 'r') as file:
data = json.load(file)
try:
## Try to access a key that doesn't exist
occupation = data["person"]["occupation"]
print(f"Occupation: {occupation}")
except KeyError as e:
print(f"Error occurred: KeyError - {e}")
## Now let's try a nested key that doesn't exist
try:
salary = data["person"]["employment"]["salary"]
print(f"Salary: {salary}")
except KeyError as e:
print(f"Error occurred: KeyError - {e}")
스크립트를 실행합니다.
python3 error_demo.py
다음과 유사한 출력을 볼 수 있습니다.
Error occurred: KeyError - 'occupation'
Error occurred: KeyError - 'salary'
보시다시피, 직접 인덱싱은 키가 존재하지 않을 때 예외를 발생시킵니다. 실제 응용 프로그램, 특히 외부 API 또는 사용자가 생성한 데이터로 작업할 때는 JSON 객체의 구조가 다를 수 있습니다. 다음 단계에서는 누락된 키를 우아하게 처리하는 중첩된 JSON 데이터에 접근하기 위한 더 안전한 방법을 살펴보겠습니다.
중첩된 JSON 데이터에 접근하기 위한 안전한 방법
실제 응용 프로그램에서는 키가 누락되거나 JSON 의 구조가 다를 수 있는 경우를 처리해야 하는 경우가 많습니다. 중첩된 JSON 데이터에 접근하기 위한 더 안전한 방법을 살펴보겠습니다.
get() 메서드 사용
딕셔너리의 get() 메서드를 사용하면 키를 찾을 수 없는 경우 기본값을 제공하여 KeyError 예외를 방지할 수 있습니다. safe_access.py라는 파일을 만들어 보겠습니다.
import json
## Load JSON from file
with open('sample.json', 'r') as file:
data = json.load(file)
## Using get() for safer access
name = data.get("person", {}).get("name", "Unknown")
## If the "occupation" key doesn't exist, "Not specified" will be returned
occupation = data.get("person", {}).get("occupation", "Not specified")
print(f"Name: {name}")
print(f"Occupation: {occupation}")
## Accessing deeply nested values with get()
company = data.get("person", {}).get("employment", {}).get("company", "Unknown")
salary = data.get("person", {}).get("employment", {}).get("salary", "Not specified")
print(f"Company: {company}")
print(f"Salary: {salary}")
## Providing default values for arrays
hobbies = data.get("person", {}).get("hobbies", [])
skills = data.get("person", {}).get("skills", ["No skills listed"])
print(f"Hobbies: {', '.join(hobbies)}")
print(f"Skills: {', '.join(skills)}")
스크립트를 실행합니다.
python3 safe_access.py
다음과 유사한 출력을 볼 수 있습니다.
Name: John Doe
Occupation: Not specified
Company: Tech Solutions Inc.
Salary: Not specified
Hobbies: reading, hiking, photography
Skills: No skills listed
"occupation" 및 "skills"와 같은 일부 키가 JSON 에 존재하지 않더라도 오류가 발생하지 않았음을 확인하십시오. 대신, 지정한 기본값을 얻었습니다.
깊이 중첩된 데이터에 대한 get() 체이닝
깊이 중첩된 JSON 구조로 작업할 때는 여러 get() 호출을 연결하면 장황해지고 읽기 어려워질 수 있습니다. 변수를 사용하여 더 읽기 쉬운 버전을 만들어 보겠습니다. chained_get.py라는 파일을 만듭니다.
import json
## Load JSON from file
with open('sample.json', 'r') as file:
data = json.load(file)
## Step-by-step approach for deeply nested values
person = data.get("person", {})
employment = person.get("employment", {})
projects = employment.get("projects", [])
## Get the first project or an empty dict if projects list is empty
first_project = projects[0] if projects else {}
project_name = first_project.get("name", "No project")
project_status = first_project.get("status", "Unknown")
print(f"Project: {project_name}, Status: {project_status}")
## Let's try a non-existent path
person = data.get("person", {})
education = person.get("education", {})
degree = education.get("degree", "Not specified")
print(f"Degree: {degree}")
스크립트를 실행합니다.
python3 chained_get.py
다음과 유사한 출력을 볼 수 있습니다.
Project: Project Alpha, Status: completed
Degree: Not specified
이 접근 방식은 중첩 수준을 별도의 변수로 나누기 때문에 더 읽기 쉽습니다. 또한 각 수준에서 기본값을 제공하므로 안전합니다.
Default Dict 사용
또 다른 접근 방식은 collections 모듈에서 Python 의 defaultdict를 사용하는 것입니다. defaultdict는 누락된 키에 대해 자동으로 기본값을 제공합니다. default_dict.py라는 파일을 만듭니다.
import json
from collections import defaultdict
## Function to create a nested defaultdict
def nested_defaultdict():
return defaultdict(nested_defaultdict)
## Load JSON from file
with open('sample.json', 'r') as file:
regular_data = json.load(file)
## Convert to defaultdict
def dict_to_defaultdict(d):
if not isinstance(d, dict):
return d
result = defaultdict(nested_defaultdict)
for k, v in d.items():
if isinstance(v, dict):
result[k] = dict_to_defaultdict(v)
elif isinstance(v, list):
result[k] = [dict_to_defaultdict(item) if isinstance(item, dict) else item for item in v]
else:
result[k] = v
return result
## Convert our data to defaultdict
data = dict_to_defaultdict(regular_data)
## Now we can access keys that don't exist without errors
print(f"Name: {data['person']['name']}")
print(f"Occupation: {data['person']['occupation']}") ## This key doesn't exist!
print(f"Education: {data['person']['education']['degree']}") ## Deeply nested non-existent path
## defaultdict returns another defaultdict for missing keys, which might not be what you want
print(f"Type of data['person']['occupation']: {type(data['person']['occupation'])}")
## To get a specific default value, you would use get() even with defaultdict
occupation = data['person'].get('occupation', 'Not specified')
print(f"Occupation with default: {occupation}")
스크립트를 실행합니다.
python3 default_dict.py
다음과 유사한 출력을 볼 수 있습니다.
Name: John Doe
Occupation: defaultdict(<function nested_defaultdict at 0x...>, {})
Education: defaultdict(<function nested_defaultdict at 0x...>, {})
Type of data['person']['occupation']: <class 'collections.defaultdict'>
Occupation with default: Not specified
defaultdict는 KeyError 예외를 방지하지만 누락된 키에 대해 다른 defaultdict를 반환하므로 원하는 기본값이 아닐 수 있습니다. 이것이 get() 메서드가 특정 기본값을 제공하는 데 더 실용적인 이유입니다.
다음 단계에서는 안전성과 유연성을 모두 갖춘 깊이 중첩된 JSON 에서 값을 추출하는 유틸리티 함수를 만드는 방법을 살펴보겠습니다.
JSON 값 추출을 위한 유틸리티 함수 만들기
이제 중첩된 JSON 데이터에 접근하는 다양한 방법을 살펴보았으므로 복잡한 중첩 구조에서 값을 더 쉽게 추출할 수 있는 유틸리티 함수를 만들어 보겠습니다. 이 함수는 get() 메서드의 안전성과 다양한 유형의 데이터를 처리할 수 있는 유연성을 결합합니다.
경로 기반 추출 함수
json_extractor.py라는 새 파일을 만듭니다.
import json
from typing import Any, List, Dict, Union, Optional
def extract_value(data: Dict, path: List[str], default: Any = None) -> Any:
"""
Safely extract a value from a nested dictionary using a path list.
Args:
data: The dictionary to extract value from
path: A list of keys representing the path to the value
default: The default value to return if the path doesn't exist
Returns:
The value at the specified path or the default value if not found
"""
current = data
for key in path:
if isinstance(current, dict) and key in current:
current = current[key]
else:
return default
return current
## Load JSON from file
with open('sample.json', 'r') as file:
data = json.load(file)
## Basic usage examples
name = extract_value(data, ["person", "name"], "Unknown")
age = extract_value(data, ["person", "age"], 0)
print(f"Name: {name}, Age: {age}")
## Extracting values that don't exist
occupation = extract_value(data, ["person", "occupation"], "Not specified")
print(f"Occupation: {occupation}")
## Extracting deeply nested values
email = extract_value(data, ["person", "contact", "email"], "No email")
phone = extract_value(data, ["person", "contact", "phone"], "No phone")
print(f"Email: {email}, Phone: {phone}")
## Extracting from arrays
if isinstance(extract_value(data, ["person", "hobbies"], []), list):
first_hobby = extract_value(data, ["person", "hobbies"], [])[0] if extract_value(data, ["person", "hobbies"], []) else "No hobbies"
else:
first_hobby = "No hobbies"
print(f"First hobby: {first_hobby}")
## Extracting from arrays of objects
projects = extract_value(data, ["person", "employment", "projects"], [])
if projects and len(projects) > 0:
first_project_name = extract_value(projects[0], ["name"], "Unknown project")
first_project_status = extract_value(projects[0], ["status"], "Unknown status")
print(f"First project: {first_project_name}, Status: {first_project_status}")
else:
print("No projects found")
스크립트를 실행합니다.
python3 json_extractor.py
다음과 유사한 출력을 볼 수 있습니다.
Name: John Doe, Age: 35
Occupation: Not specified
Email: john.doe@example.com, Phone: 555-123-4567
First hobby: reading
First project: Project Alpha, Status: completed
경로 문자열을 사용한 향상된 JSON 추출기
이제 추출기를 향상시켜 경로에 대한 점 표기법을 지원하여 사용하기 더 직관적으로 만들겠습니다. enhanced_extractor.py라는 파일을 만듭니다.
import json
from typing import Any, Dict, List, Union
def get_nested_value(data: Dict, path_string: str, default: Any = None) -> Any:
"""
Safely extract a value from a nested dictionary using a dot-separated path string.
Args:
data: The dictionary to extract value from
path_string: A dot-separated string representing the path to the value
default: The default value to return if the path doesn't exist
Returns:
The value at the specified path or the default value if not found
"""
## Convert the path string to a list of keys
path = path_string.split(".")
## Start with the full dictionary
current = data
## Follow the path
for key in path:
## Handle list indexing with [n] notation
if key.endswith("]") and "[" in key:
list_key, index_str = key.split("[")
index = int(index_str[:-1]) ## Remove the closing bracket and convert to int
## Get the list
if list_key: ## If there's a key before the bracket
if not isinstance(current, dict) or list_key not in current:
return default
current = current[list_key]
## Get the item at the specified index
if not isinstance(current, list) or index >= len(current):
return default
current = current[index]
else:
## Regular dictionary key
if not isinstance(current, dict) or key not in current:
return default
current = current[key]
return current
## Load JSON from file
with open('sample.json', 'r') as file:
data = json.load(file)
## Test the enhanced extractor
print("Basic access:")
print(f"Name: {get_nested_value(data, 'person.name', 'Unknown')}")
print(f"Age: {get_nested_value(data, 'person.age', 0)}")
print(f"Occupation: {get_nested_value(data, 'person.occupation', 'Not specified')}")
print("\nNested access:")
print(f"Email: {get_nested_value(data, 'person.contact.email', 'No email')}")
print(f"City: {get_nested_value(data, 'person.address.city', 'Unknown city')}")
print("\nArray access:")
print(f"First hobby: {get_nested_value(data, 'person.hobbies[0]', 'No hobbies')}")
print(f"Second hobby: {get_nested_value(data, 'person.hobbies[1]', 'No second hobby')}")
print(f"Non-existent hobby: {get_nested_value(data, 'person.hobbies[10]', 'No such hobby')}")
print("\nComplex access:")
print(f"Company: {get_nested_value(data, 'person.employment.company', 'Unknown company')}")
print(f"First project name: {get_nested_value(data, 'person.employment.projects[0].name', 'No project')}")
print(f"Second project status: {get_nested_value(data, 'person.employment.projects[1].status', 'Unknown status')}")
print(f"Non-existent project: {get_nested_value(data, 'person.employment.projects[2].name', 'No such project')}")
print(f"Education: {get_nested_value(data, 'person.education.degree', 'No education info')}")
스크립트를 실행합니다.
python3 enhanced_extractor.py
다음과 유사한 출력을 볼 수 있습니다.
Basic access:
Name: John Doe
Age: 35
Occupation: Not specified
Nested access:
Email: john.doe@example.com
City: Anytown
Array access:
First hobby: reading
Second hobby: hiking
Non-existent hobby: No such hobby
Complex access:
Company: Tech Solutions Inc.
First project name: Project Alpha
Second project status: in-progress
Non-existent project: No such project
Education: No education info
실제 적용
이제 향상된 JSON 추출기를 보다 복잡한 실제 시나리오에 적용해 보겠습니다. practical_example.py라는 파일을 만듭니다.
import json
import os
from typing import Any, Dict, List
## Import our enhanced extractor function
from enhanced_extractor import get_nested_value
## Create a more complex JSON structure for reporting
report_data = {
"company": "Global Analytics Ltd.",
"report_date": "2023-11-01",
"departments": [
{
"name": "Engineering",
"manager": "Alice Johnson",
"employee_count": 45,
"projects": [
{"id": "E001", "name": "API Gateway", "status": "completed", "budget": 125000},
{"id": "E002", "name": "Mobile App", "status": "in-progress", "budget": 200000}
]
},
{
"name": "Marketing",
"manager": "Bob Smith",
"employee_count": 28,
"projects": [
{"id": "M001", "name": "Q4 Campaign", "status": "planning", "budget": 75000}
]
},
{
"name": "Customer Support",
"manager": "Carol Williams",
"employee_count": 32,
"projects": []
}
],
"financial": {
"current_quarter": {
"revenue": 2500000,
"expenses": 1800000,
"profit_margin": 0.28
},
"previous_quarter": {
"revenue": 2300000,
"expenses": 1750000,
"profit_margin": 0.24
}
}
}
## Save this data to a JSON file for demonstration
with open('report.json', 'w') as file:
json.dump(report_data, file, indent=2)
print("Report data saved to report.json")
## Now let's extract useful information from this report
def generate_summary(data: Dict) -> str:
"""Generate a summary of the company report"""
company = get_nested_value(data, "company", "Unknown Company")
report_date = get_nested_value(data, "report_date", "Unknown Date")
## Financial summary
current_revenue = get_nested_value(data, "financial.current_quarter.revenue", 0)
previous_revenue = get_nested_value(data, "financial.previous_quarter.revenue", 0)
revenue_change = current_revenue - previous_revenue
revenue_change_percent = (revenue_change / previous_revenue * 100) if previous_revenue > 0 else 0
## Department summary
departments = get_nested_value(data, "departments", [])
total_employees = sum(get_nested_value(dept, "employee_count", 0) for dept in departments)
## Project counts
total_projects = sum(len(get_nested_value(dept, "projects", [])) for dept in departments)
completed_projects = sum(
1 for dept in departments
for proj in get_nested_value(dept, "projects", [])
if get_nested_value(proj, "status", "") == "completed"
)
## Generate summary text
summary = f"Company Report Summary for {company} as of {report_date}\n"
summary += "=" * 50 + "\n\n"
summary += "Financial Overview:\n"
summary += f"- Current Quarter Revenue: ${current_revenue:,}\n"
summary += f"- Revenue Change: ${revenue_change:,} ({revenue_change_percent:.1f}%)\n\n"
summary += "Operational Overview:\n"
summary += f"- Total Departments: {len(departments)}\n"
summary += f"- Total Employees: {total_employees}\n"
summary += f"- Total Projects: {total_projects}\n"
summary += f"- Completed Projects: {completed_projects}\n\n"
summary += "Department Details:\n"
for i, dept in enumerate(departments):
dept_name = get_nested_value(dept, "name", f"Department {i+1}")
manager = get_nested_value(dept, "manager", "No manager")
employees = get_nested_value(dept, "employee_count", 0)
projects = get_nested_value(dept, "projects", [])
summary += f"- {dept_name} (Manager: {manager})\n"
summary += f" * Employees: {employees}\n"
summary += f" * Projects: {len(projects)}\n"
if projects:
for proj in projects:
proj_name = get_nested_value(proj, "name", "Unnamed Project")
proj_status = get_nested_value(proj, "status", "unknown")
proj_budget = get_nested_value(proj, "budget", 0)
summary += f" - {proj_name} (Status: {proj_status}, Budget: ${proj_budget:,})\n"
else:
summary += " - No active projects\n"
summary += "\n"
return summary
## Generate and display the summary
summary = generate_summary(report_data)
print("\nGenerated Report Summary:")
print(summary)
## Save the summary to a file
with open('report_summary.txt', 'w') as file:
file.write(summary)
print("Summary saved to report_summary.txt")
스크립트를 실행합니다.
python3 practical_example.py
보고서 데이터가 저장되었음을 확인하는 메시지가 표시된 다음 회사 보고서에 대한 자세한 요약이 표시됩니다.
출력 파일을 확인합니다.
cat report_summary.txt
이 실제 예제는 JSON 추출기 유틸리티를 사용하여 누락된 데이터를 우아하게 처리하는 강력한 보고 도구를 구축하는 방법을 보여줍니다. get_nested_value 함수를 사용하면 KeyError 또는 NoneType 예외에 대해 걱정하지 않고 복잡한 중첩 구조에서 안전하게 값을 추출할 수 있습니다.
모범 사례 요약
이 랩에서 살펴본 기술을 기반으로 중첩된 JSON 객체에서 값을 추출하기 위한 모범 사례는 다음과 같습니다.
get()메서드 사용: 직접 인덱싱 대신get()메서드를 사용하여 누락된 키에 대한 기본값을 제공합니다.- 유틸리티 함수 만들기: 반복적인 코드를 피하기 위해 일반적인 JSON 추출 패턴에 대한 유틸리티 함수를 만듭니다.
- 누락된 경로를 우아하게 처리: 적절한 기본값을 제공합니다.
- 값 유형 확인: 오류를 방지하기 전에 값을 처리하기 전에 유형을 확인합니다 (예: 인덱스에 접근하기 전에 값이 목록인지 확인).
- 복잡한 경로 나누기: 가독성을 높이기 위해 복잡한 경로를 별도의 변수로 나눕니다.
- 점 표기법을 사용한 경로 문자열 사용: 중첩된 값에 더 직관적으로 접근합니다.
- 추출 코드 문서화: JSON 구조에서 무엇을 찾고 있는지 명확하게 합니다.
이러한 모범 사례를 따르면 Python 에서 중첩된 JSON 객체로 작업하기 위한 보다 강력하고 유지 관리 가능한 코드를 작성할 수 있습니다.
요약
이 랩에서는 Python 에서 중첩된 JSON 객체에서 값을 추출하기 위한 실용적인 기술을 배웠습니다. 중첩된 JSON 의 구조와 Python 에서 JSON 데이터를 로드하는 방법을 이해하는 것으로 시작했습니다. 그런 다음 기본 인덱싱부터 더 강력한 접근 방식까지 중첩된 데이터에 접근하는 다양한 방법을 탐구했습니다.
이 랩의 주요 내용은 다음과 같습니다.
JSON 구조 이해: 중첩된 JSON 객체의 계층적 특성을 인식하는 것은 해당 값을 효과적으로 접근하는 데 필수적입니다.
기본 접근 방식: JSON 데이터의 구조를 확신하는 경우 대괄호를 사용한 직접 인덱싱이 작동합니다.
안전한 접근 기술:
get()메서드를 사용하면 누락된 키에 대한 기본값을 제공하여 불확실한 데이터 구조를 처리할 때 코드를 더욱 강력하게 만들 수 있습니다.유틸리티 함수: JSON 추출을 위한 특수 함수를 만들면 코드를 크게 단순화하고 유지 관리성을 높일 수 있습니다.
경로 기반 접근: 점 표기법을 사용한 경로 문자열을 사용하면 깊이 중첩된 값에 직관적으로 접근할 수 있습니다.
실제 적용: 이러한 기술을 실제 시나리오에 적용하면 강력한 데이터 처리 도구를 구축하는 데 도움이 됩니다.
이러한 모범 사례를 따르면 구조가 불규칙하거나 누락된 값을 포함하는 경우에도 중첩된 JSON 데이터의 복잡성을 우아하게 처리하는 더욱 탄력적인 코드를 작성할 수 있습니다.



