실습: JSON 데이터 추출기 구축
복잡한 JSON 구조에서 특정 정보를 추출하는 프로그램을 만들어 지식을 실천에 옮겨 봅시다. 이는 API 에서 JSON 데이터를 수신하고 이를 처리해야 하는 실제 시나리오를 나타낼 수 있습니다.
-
WebIDE 에서 새 파일을 만들고 /home/labex/project/json_practice 디렉토리에 json_extractor.py로 저장합니다.
-
json_extractor.py에 다음 코드를 추가합니다.
import json
## A complex nested JSON structure (e.g., from a weather API)
weather_data = {
"location": {
"name": "New York",
"region": "New York",
"country": "United States of America",
"lat": 40.71,
"lon": -74.01,
"timezone": "America/New_York"
},
"current": {
"temp_c": 22.0,
"temp_f": 71.6,
"condition": {
"text": "Partly cloudy",
"icon": "//cdn.weatherapi.com/weather/64x64/day/116.png",
"code": 1003
},
"wind_mph": 6.9,
"wind_kph": 11.2,
"wind_dir": "ENE",
"humidity": 65,
"cloud": 75,
"feelslike_c": 22.0,
"feelslike_f": 71.6
},
"forecast": {
"forecastday": [
{
"date": "2023-09-20",
"day": {
"maxtemp_c": 24.3,
"maxtemp_f": 75.7,
"mintemp_c": 18.6,
"mintemp_f": 65.5,
"condition": {
"text": "Patchy rain possible",
"icon": "//cdn.weatherapi.com/weather/64x64/day/176.png",
"code": 1063
},
"daily_chance_of_rain": 85
},
"astro": {
"sunrise": "06:41 AM",
"sunset": "07:01 PM",
"moonrise": "10:15 AM",
"moonset": "08:52 PM"
},
"hour": [
{
"time": "2023-09-20 00:00",
"temp_c": 20.1,
"condition": {
"text": "Clear",
"icon": "//cdn.weatherapi.com/weather/64x64/night/113.png",
"code": 1000
},
"chance_of_rain": 0
},
{
"time": "2023-09-20 12:00",
"temp_c": 23.9,
"condition": {
"text": "Overcast",
"icon": "//cdn.weatherapi.com/weather/64x64/day/122.png",
"code": 1009
},
"chance_of_rain": 20
}
]
},
{
"date": "2023-09-21",
"day": {
"maxtemp_c": 21.2,
"maxtemp_f": 70.2,
"mintemp_c": 16.7,
"mintemp_f": 62.1,
"condition": {
"text": "Heavy rain",
"icon": "//cdn.weatherapi.com/weather/64x64/day/308.png",
"code": 1195
},
"daily_chance_of_rain": 92
},
"astro": {
"sunrise": "06:42 AM",
"sunset": "06:59 PM",
"moonrise": "11:30 AM",
"moonset": "09:15 PM"
}
}
]
}
}
def extract_weather_summary(data):
"""
Extract and format a weather summary from the provided data.
"""
try:
## Location information
location = data.get("location", {})
location_name = location.get("name", "Unknown")
country = location.get("country", "Unknown")
## Current weather
current = data.get("current", {})
temp_c = current.get("temp_c", "N/A")
temp_f = current.get("temp_f", "N/A")
condition = current.get("condition", {}).get("text", "Unknown")
humidity = current.get("humidity", "N/A")
## Forecast
forecast_days = data.get("forecast", {}).get("forecastday", [])
## Build summary string
summary = f"Weather Summary for {location_name}, {country}\n"
summary += f"==================================================\n\n"
summary += f"Current Conditions:\n"
summary += f" Temperature: {temp_c}°C ({temp_f}°F)\n"
summary += f" Condition: {condition}\n"
summary += f" Humidity: {humidity}%\n\n"
if forecast_days:
summary += "Forecast:\n"
for day_data in forecast_days:
date = day_data.get("date", "Unknown date")
day = day_data.get("day", {})
max_temp = day.get("maxtemp_c", "N/A")
min_temp = day.get("mintemp_c", "N/A")
condition = day.get("condition", {}).get("text", "Unknown")
rain_chance = day.get("daily_chance_of_rain", "N/A")
summary += f" {date}:\n"
summary += f" High: {max_temp}°C, Low: {min_temp}°C\n"
summary += f" Condition: {condition}\n"
summary += f" Chance of Rain: {rain_chance}%\n"
## Get sunrise and sunset times if available
astro = day_data.get("astro", {})
if astro:
sunrise = astro.get("sunrise", "N/A")
sunset = astro.get("sunset", "N/A")
summary += f" Sunrise: {sunrise}, Sunset: {sunset}\n"
summary += "\n"
return summary
except Exception as e:
return f"Error extracting weather data: {str(e)}"
## Print the full JSON data
print("Original Weather Data:")
print(json.dumps(weather_data, indent=2))
print("\n" + "-" * 60 + "\n")
## Extract and print the weather summary
weather_summary = extract_weather_summary(weather_data)
print(weather_summary)
## Save the summary to a file
with open("weather_summary.txt", "w") as file:
file.write(weather_summary)
print("\nWeather summary has been saved to 'weather_summary.txt'")
- 터미널에서 스크립트를 실행합니다.
cd /home/labex/project/json_practice
python3 json_extractor.py
- 스크립트를 실행한 후 생성된 요약 파일을 볼 수 있습니다.
cat weather_summary.txt
복잡한 JSON 구조에서 추출된 형식화된 날씨 요약을 볼 수 있습니다.
JSON 추출기 이해
이 실습에서는 중첩된 JSON 데이터로 작업하기 위한 몇 가지 중요한 개념을 보여줍니다.
-
안전한 데이터 추출
- 누락된 키를 처리하기 위해 기본값을 사용하여
get() 메서드 사용
- 연결된
get() 호출로 중첩된 데이터에 액세스
- try-except 블록을 사용한 오류 처리
-
데이터 변환
- JSON 데이터를 사람이 읽을 수 있는 형식으로 변환
- 여러 항목을 처리하기 위해 중첩된 배열을 반복
- 복잡한 구조에서 관련 정보만 추출
-
방어적 프로그래밍
- 잠재적인 문제를 예상하고 처리
- 데이터가 누락된 경우 기본값 제공
- 프로그램 충돌을 방지하기 위해 예외를 포착
JSON 데이터를 추출, 변환 및 표시하는 이 패턴은 다음과 같은 많은 실제 응용 프로그램에서 일반적입니다.
- API 응답 처리
- 데이터에서 보고서 생성
- 사용자에게 정보 필터링 및 표시
이러한 패턴을 따르면 복잡성에 관계없이 JSON 데이터를 안정적으로 사용할 수 있습니다.