Easiest way to serialize a simple class object with simplejson?

前端 未结 7 2030
萌比男神i
萌比男神i 2020-12-07 15:55

I\'m trying to serialize a list of python objects with JSON (using simplejson) and am getting the error that the object \"is not JSON serializable\".

The class is a

7条回答
  •  南笙
    南笙 (楼主)
    2020-12-07 16:41

    I have a similar problem but the json.dump function is not called by me. So, to make MyClass JSON serializable without giving a custom encoder to json.dump you have to Monkey patch the json encoder.

    First create your encoder in your module my_module:

    import json
    
    class JSONEncoder(json.JSONEncoder):
        """To make MyClass JSON serializable you have to Monkey patch the json
        encoder with the following code:
        >>> import json
        >>> import my_module
        >>> json.JSONEncoder.default = my_module.JSONEncoder.default
        """
        def default(self, o):
            """For JSON serialization."""
            if isinstance(o, MyClass):
                return o.__repr__()
            else:
                return super(self,o)
    
    class MyClass:
        def __repr__(self):
            return "my class representation"
    

    Then as it is described in the comment, monkey patch the json encoder:

    import json
    import my_module
    json.JSONEncoder.default = my_module.JSONEncoder.default
    

    Now, even an call of json.dump in an external library (where you cannot change the cls parameter) will work for your my_module.MyClass objects.

提交回复
热议问题