Pythonでは、自分で定義したクラスのオブジェクトをJSON形式に変換する(エンコード)方法と、その逆のJSON形式からクラスオブジェクトに戻す(デコード)方法があります。
エンコード
Pythonのjson
ライブラリのdump
やdumps
メソッドは、cls
という引数を取ります。ここに自分で定義したエンコーダを指定することができます。以下にその例を示します。
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)
デコード
デコードも同様に、json
ライブラリのload
やloads
メソッドは、cls
という引数を取ります。ここに自分で定義したデコーダを指定することができます。以下にその例を示します。
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)
以上のように、Pythonのjson
ライブラリを使えば、自分で定義したクラスのオブジェクトをJSON形式に変換し、またその逆の操作も可能です。