사용자 정의 JSON 디코딩
Coddy의 Python JSON 코스 레슨 — 9개 중 9번째.
커스텀 JSON 디코딩은 JSON 데이터가 Python 객체로 변환되는 방식을 제어할 수 있게 해주는 Python json 모듈의 고급 기능입니다. 이는 복잡한 데이터 구조를 다루거나 JSON 데이터로부터 특정 Python 객체를 생성하고자 할 때 특히 유용합니다.
JSONDecoder 클래스
커스텀 JSON 디코딩을 구현하려면 json.JSONDecoder 클래스를 상속받고 object_hook 메서드를 오버라이드해야 합니다:
import json
class CustomDecoder(json.JSONDecoder):
def object_hook(self, dct):
# 여기에 커스텀 디코딩 로직 작성
return dct
커스텀 디코더 사용하기
커스텀 디코더를 정의한 후에는 json.loads() 또는 json.load()와 함께 사용할 수 있습니다:
decoded_object = json.loads(json_string, cls=CustomDecoder)
예제: 커스텀 객체로 디코딩하기
JSON 데이터를 커스텀 Python 객체로 디코딩하는 실용적인 예제를 살펴보겠습니다:
import json
from datetime import datetime
class Person:
def __init__(self, name, birthdate):
self.name = name
self.birthdate = birthdate
class CustomDecoder(json.JSONDecoder):
def object_hook(self, dct):
if 'name' in dct and 'birthdate' in dct:
return Person(dct['name'], datetime.fromisoformat(dct['birthdate']))
return dct
json_string = '{"name": "Alice", "birthdate": "1990-05-15"}'
person = json.loads(json_string, cls=CustomDecoder)
print(type(person)) # 출력: <class '__main__.Person'>
print(person.name) # 출력: Alice
print(person.birthdate) # 출력: 1990-05-15 00:00:00
주요 사항
object_hook메서드는 디코딩된 각 객체에 대해 호출됩니다.- 특정 키나 패턴을 확인하여 객체를 디코딩하는 방법을 결정할 수 있습니다.
- 해당 구조에 대해 커스텀 디코딩이 필요하지 않은 경우 객체를 그대로 반환합니다.
- 커스텀 디코더는 JSON 데이터로부터 도메인 특화 객체를 직접 생성하는 데 유용합니다.
커스텀 JSON 디코더를 사용하면 JSON 데이터를 Python 애플리케이션의 객체 모델에 원활하게 통합할 수 있으며, 데이터 역직렬화를 더 유연하고 특정 요구 사항에 맞게 조정할 수 있습니다.
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.
챌린지
쉬움기상 데이터 시스템을 위한 사용자 정의 JSON 디코더를 만드세요. 이 디코더는 JSON 문자열을 특정 속성과 변환 규칙을 가진 WeatherData 객체로 변환해야 합니다. 다음 사항을 구현하세요:
location,temperature,humidity,conditions속성을 가진WeatherData클래스를 정의합니다.- 다음 기능을 수행하는 사용자 정의
JSONDecoder서브클래스를 생성합니다:- 온도를 화씨(Fahrenheit)에서 섭씨(Celsius)로 변환하고, 소수점 첫째 자리까지 반올림합니다.
- 습도(humidity)가 백분율로 표시되도록 합니다 (예: 0.65는 65%가 됨).
- 기상 조건(conditions) 문자열의 각 단어 첫 글자를 대문자로 변환합니다.
- JSON 문자열을 받아 사용자 정의 디코더를 사용하여 파싱하고, 형식화된 기상 데이터 문자열을 반환하는 함수를 구현합니다.
다음과 같은 입력이 제공됩니다:
{"location": "new york", "temperature": 72, "humidity": 0.65, "conditions": "partly cloudy"}
결과로 나온 형식화된 문자열을 다음 형식으로 출력하세요:
"Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"
직접 해보기
Here's a suitable starter code for the challenge:
```python
import json
# Read input
json_string = input()
class WeatherData:
def __init__(self, location, temperature, humidity, conditions):
self.location = location
self.temperature = temperature
self.humidity = humidity
self.conditions = conditions
class CustomJSONDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, dct):
# TODO: Implement the custom decoding logic here
pass
def parse_weather_data(json_string):
# TODO: Implement the parsing function here
pass
# TODO: Use the CustomJSONDecoder and parse_weather_data function to process the input
# Placeholder for the result
result = "Location: [location], Temperature: [temp]°C, Humidity: [humidity], Conditions: [conditions]"
# Output the result
print(result)
```