How to dump a Python dictionary to JSON when keys are non-trivial objects?

后端 未结 4 1093
深忆病人
深忆病人 2021-02-08 05:54
import datetime, json
x = {\'alpha\': {datetime.date.today(): \'abcde\'}}
print json.dumps(x)

The above code fails with a TypeError since

4条回答
  •  孤街浪徒
    2021-02-08 05:55

    If you really need to do it, you can monkeypatch json.encoder:

    from _json import encode_basestring_ascii  # used when ensure_ascii=True (which is the default where you want everything to be ascii)
    from _json import encode_basestring  # used in any other case
    
    def _patched_encode_basestring(o):
        """
        Monkey-patching Python's json serializer so it can serialize keys that are not string!
        You can monkey patch the ascii one the same way.
        """
        if isinstance(o, MyClass):
            return my_serialize(o)
        return encode_basestring(o)
    
    
    json.encoder.encode_basestring = _patched_encode_basestring
    

提交回复
热议问题