Pythonで自分で定義したクラスのオブジェクトをJSON形式にする方法と、JSON形式から戻す方法について説明します。
PythonクラスをJSONシリアライズ可能にする
Pythonの組み込みモジュールであるjsonは、直接JSONとして変換可能なPythonの基本的な型のみを扱うことができます。したがって、カスタムPythonオブジェクトをJSON形式にエンコードしようとすると、TypeError: Object of type SampleClass is not JSON serializable
というエラーが発生します。
この問題を解決するためには、クラスをJSONシリアライズ可能にするカスタムエンコーダを作成する必要があります。
import json
from json import JSONEncoder
class Employee:
def __init__(self, name, salary, address):
self.name = name
self.salary = salary
self.address = address
class Address:
def __init__(self, city, street, pin):
self.city = city
self.street = street
self.pin = pin
# JSONEncoderクラスをサブクラス化
class EmployeeEncoder(JSONEncoder):
def default(self, o):
return o.__dict__
address = Address("Alpharetta", "7258 Spring Street", "30004")
employee = Employee("John", 9000, address)
print("Encode Employee Object into JSON formatted Data using custom JSONEncoder")
print(EmployeeEncoder().encode(employee))
上記のコードでは、EmployeeEncoder
というカスタムエンコーダを作成し、Employee
クラスのオブジェクトをJSON形式にエンコードしています。
jsonpickleモジュールを使用する
jsonpickleは、複雑なPythonオブジェクトを扱うためのPythonライブラリです。このライブラリを使用すると、複雑なPythonオブジェクトをJSONにシリアライズしたり、JSONから複雑なPythonオブジェクトにデシリアライズしたりすることができます。
以上がPythonクラスをJSONシリアライズ可能にする方法についての説明です。これらの方法を試してみて、PythonのクラスとJSONの相互変換をマスターしましょう。