LoginSignup
2
4

More than 5 years have passed since last update.

JSONからPythonオブジェクトを生成する方法

Posted at

json – JavaScript Object Notation シリアライザ - Python Module of the Week
の写経である

なんとなくの説明は JSONからPerlオブジェクトを生成する方法 - Qiita を参照のこと

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
"""
2
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
4