カスタム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サブクラスを作成します:- 温度を華氏から摂氏に変換し、小数点第1位で四捨五入します。
- 湿度がパーセンテージとして表されるようにします(例: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)
```PythonでのJSONのすべてのレッスン
自分で練習してみよう: Pythonオンラインコンパイラ