json – JavaScript Object Notation Serializer -Python Module of the Week Is a sutra copy of
Please refer to How to create a Perl object from JSON -Qiita for some explanation.
class MyObj(object):
def __init__(self, s, y):
self.s = s
self.y = y
def __repr__(self):
return '<MyObj(%s)>' % self.s
def main():
import json
obj = MyObj('instance value goes here', "a")
print(obj)
# print('First attempt')
try:
print(json.dumps(obj))
except TypeError, err:
print("ERROR:", err)
def convert_to_builtin_type(obj):
# print('default(', repr(obj), ')')
# Convert objects to a dictionary of their representation
d = {'__class__': obj.__class__.__name__,
'__module__': obj.__module__,
}
d.update(obj.__dict__)
return d
def dict_to_object(d):
if '__class__' in d:
class_name = d.pop('__class__')
module_name = d.pop('__module__')
module = __import__(module_name)
# print('MODULE:', module)
class_ = getattr(module, class_name)
# print('CLASS:', class_)
args = dict((key.encode('ascii'), value) for key, value in d.items())
# print('INSTANCE ARGS:', args)
inst = class_(**args)
else:
inst = d
return inst
# print('With default')
json_txt = json.dumps(obj, default=convert_to_builtin_type)
print(json_txt)
obj2 = json.loads(json_txt, object_hook=dict_to_object)
print(obj2)
print(obj2.s)
if __name__ == '__main__':
main()
exit(0)
"""
<MyObj(instance value goes here)>
ERROR: <MyObj(instance value goes here)> is not JSON serializable
{"y": "a", "s": "instance value goes here", "__module__": "__main__", "__class__": "MyObj"}
<MyObj(instance value goes here)>
instance value goes here
"""
Recommended Posts