Quantcast
Channel: User Mark - Stack Overflow
Viewing all articles
Browse latest Browse all 44

Answer by Mark for Why does JSON serialization of datetime objects in Python not work out of the box for datetime objects?

$
0
0

If you want to get encoding and decoding of datetimes without having to implement it, you can use json_tricks, which is a wrapper that adds encoding and decoding for various popular types. Just install:

pip install json_tricks

and then import from json_tricks instead of json, e.g.:

from json_tricks import dumps, loadsjson = dumps({'name': 'MyName', 'birthday': datetime.datetime(1992, 5, 23, 18, 38, 23, 37566)})me = loads(json)

Disclaimer: it's made by me. Because I had the same problem.


If you want to automatically serialize anything that can be stringified, you can do that with just the standard implementation very easily:

dumps(obj, default=str)

But note that this has disadvantages, e.g., none of it will be deserialized without extra effort, and maybe sometimes you just don't want to serialize something (like a function of a big NumPy array), but get a warning instead, which this method will silence.


Viewing all articles
Browse latest Browse all 44

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>