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

后端 未结 4 1099
深忆病人
深忆病人 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
    
    0 讨论(0)
  • 2021-02-08 06:12

    http://jsonpickle.github.io/ might be what you want. When facing a similar issue, I ended up doing:

    to_save = jsonpickle.encode(THE_THING, unpicklable=False, max_depth=4, make_refs=False)
    
    0 讨论(0)
  • 2021-02-08 06:19

    You can extend json.JSONEncoder to create your own encoder which will be able to deal with datetime.datetime objects (or objects of any type you desire) in such a way that a string is created which can be reproduced as a new datetime.datetime instance. I believe it should be as simple as having json.JSONEncoder call repr() on your datetime.datetime instances.

    The procedure on how to do so is described in the json module docs.

    The json module checks the type of each value it needs to encode and by default it only knows how to handle dicts, lists, tuples, strs, unicode objects, int, long, float, boolean and none :-)

    Also of importance for you might be the skipkeys argument to the JSONEncoder.


    After reading your comments I have concluded that there is no easy solution to have JSONEncoder encode the keys of dictionaries with a custom function. If you are interested you can look at the source and the methods iterencode() which calls _iterencode() which calls _iterencode_dict() which is where the type error gets raised.

    Easiest for you would be to create a new dict with isoformatted keys like this:

    import datetime, json
    
    D = {datetime.datetime.now(): 'foo',
         datetime.datetime.now(): 'bar'}
    
    new_D = {}
    
    for k,v in D.iteritems():
      new_D[k.isoformat()] = v
    
    json.dumps(new_D)
    

    Which returns '{"2010-09-15T23:24:36.169710": "foo", "2010-09-15T23:24:36.169723": "bar"}'. For niceties, wrap it in a function :-)

    0 讨论(0)
  • 2021-02-08 06:22

    you can do x = {'alpha': {datetime.date.today().strftime('%d-%m-%Y'): 'abcde'}}

    0 讨论(0)
提交回复
热议问题