-
Notifications
You must be signed in to change notification settings - Fork 5
User friendly JSON dumps
Roberto Prevato edited this page Sep 21, 2019
·
6 revisions
essentials
includes an user-friendly json.JSONEncoder
class, handling these common objects:
datetime
date
time
UUID
bytes
These types cause a TypeError
exception when using the default JSONEncoder
class.
Example:
from datetime import datetime, date, time
from essentials import json
# a datetime is serialized in isoformat
data = json.dumps({'value': datetime(2016, 3, 26, 3, 0, 0)})
assert '{"value": "2016-03-26T03:00:00"}' == data
# a date is serialized in YYYY-MM-DD format
data = json.dumps({'value': date(2016, 3, 26)})
assert '{"value": "2016-03-26"}' == data
# a time is serialized in hh:mm:ss format
data = json.dumps({'value': time(10, 30, 15)})
assert '{"value": "10:30:15"}' == data
# bytes are first base64 URL safe encoded, then decoded into UTF8 strings
data = json.dumps({'value': b'Lorem ipsum dolor sit amet'})
assert '{"value": "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ="}' == data