serialize json date / microsoft extension
Bertrand Le Roy describes how Microsoft added a Date object extension to JSON in a compatible fashion to implement serialization and serialization of timezone agnostic datetimes.
Our current approach is using a small loophole in the JSON specs. In a JSON string literal, you may (or may not) escape some characters. Among those characters, weirdly enough, there is the slash character (
'/'
). This is weird because there actually is no reason that I can think of why you’d want to do that. We’ve used it to our benefit to disambiguate a string from a date literal.The new format is
"\/Date(1198908717056)\/"
where the number is again the number of milliseconds since January 1st 1970 UTC.
I actually kind of like the hack. So, here is an implementation for Python: jsonext.py (view)
Before:
>>> import datetime, json
>>> encoded = json.dumps(datetime.date.today())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
...
File "/usr/lib/python2.6/json/encoder.py", line 344, in default
raise TypeError(repr(o) + " is not JSON serializable")
TypeError: datetime.date(2012, 6, 21) is not JSON serializable
After:
>>> import datetime, json, jsonext
>>> encoded = json.dumps(datetime.date.today(), cls=jsonext.ExtendedJSONEncoder)
>>> decoded = json.loads(encoded, cls=jsonext.ExtendedJSONDecoder)
>>> print repr(decoded)
datetime.datetime(2012, 6, 21, 0, 0)