Menu
Coddy logo textTech

Custom JSON Decoding

Coddyの「Python JSON」コースのレッスン 9/9。

カスタムJSONデコーディングは、Pythonのjsonモジュールの高度な機能であり、JSONデータがどのようにPythonオブジェクトに変換されるかを制御できます。これは、複雑なデータ構造を扱う場合や、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))  # Output: <class '__main__.Person'>
print(person.name)   # Output: Alice
print(person.birthdate)  # Output: 1990-05-15 00:00:00

主なポイント

  • object_hookメソッドは、デコードされた各オブジェクトに対して呼び出されます。
  • 特定のキーやパターンをチェックして、オブジェクトをどのようにデコードするかを決定できます。
  • その特定の構造に対してカスタムデコーディングが必要ない場合は、オブジェクトをそのまま返します。
  • カスタムデコーダーは、JSONデータからドメイン固有のオブジェクトを直接作成するのに役立ちます。

カスタムJSONデコーダーを使用することで、JSONデータをPythonアプリケーションのオブジェクトモデルにシームレスに統合でき、データのデシリアライズをより柔軟に、特定のニーズに合わせることができます。

quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

challenge icon

チャレンジ

簡単

気象データシステム用のカスタムJSONデコーダーを作成してください。このデコーダーは、JSON文字列を特定の属性と変換を持つ WeatherData オブジェクトに変換する必要があります。以下を実装してください:

  1. locationtemperaturehumidity、および conditions という属性を持つ WeatherData クラスを定義します。
  2. 以下の処理を行うカスタム JSONDecoder サブクラスを作成します:
    • 温度を華氏から摂氏に変換し、小数点第1位で四捨五入します。
    • 湿度がパーセンテージとして表されるようにします(例:0.65 は 65% になります)。
    • conditions 文字列の各単語の先頭を大文字にします。
  3. 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のすべてのレッスン