Pythonで自分で定義したクラスのオブジェクトをJSON形式に変換する方法と、その逆の変換方法について説明します。
PythonクラスオブジェクトをJSONに変換する
Pythonの json モジュールの dumps メソッドを使用します。このメソッドはPythonオブジェクトをJSON文字列に変換します。以下に例を示します。
import json
from datetime import date
class MyA:
def __init__(self, i=0, d=date.today()):
self.i = i
self.d = d
class MyEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, date):
return {'_type': 'date', 'value': o.toordinal()}
if isinstance(o, MyA):
return {'_type': 'MyA', 'value': o.__dict__}
return json.JSONEncoder.default(self, o)
a = MyA(100, date(year=2345, month=6, day=12))
js = json.dumps(a, cls=MyEncoder)
print(js)
このコードでは、MyAというクラスのインスタンスをJSONに変換しています。MyEncoderというカスタムエンコーダを定義し、json.dumpsメソッドの cls 引数に渡しています。
JSONをPythonクラスオブジェクトに変換する
JSON文字列をPythonのクラスオブジェクトに変換するには、json モジュールの loads メソッドを使用します。このメソッドはJSON文字列をPythonオブジェクトに変換します。以下に例を示します。
class MyDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
json.JSONDecoder.__init__(self, object_hook=self.object_hook, *args, **kwargs)
def object_hook(self, o):
if '_type' not in o:
return o
type = o['_type']
if type == 'date':
return date.fromordinal(o['value'])
elif type == 'MyA':
return MyA(**o['value'])
b = json.loads(js, cls=MyDecoder)
print(b.i, b.d)
このコードでは、JSON文字列をMyAクラスのインスタンスに変換しています。MyDecoderというカスタムデコーダを定義し、json.loadsメソッドの cls 引数に渡しています。
以上がPythonでクラスオブジェクトをJSONに変換し、その逆を行う基本的な方法です。これらの方法を理解し活用することで、PythonのクラスオブジェクトとJSONの間でデータを効率的にやり取りすることが可能になります。.