You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The default json.JSONEncoder class, when using json built-in module, throws a TypeError exception when trying to serialize common objects such as UUID, datetime, date.
essentials includes a more user-friendly encoder class that handles these objects:
datetime
date
time
UUID
bytes
dataclasses.dataclass
instances of classes implementing a dict() method, like pydantic BaseModel
Example:
fromdatetimeimportdatetime, date, timefromessentialsimportjson# a datetime is serialized in isoformatdata=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 formatdata=json.dumps({'value': date(2016, 3, 26)})
assert'{"value": "2016-03-26"}'==data# a time is serialized in hh:mm:ss formatdata=json.dumps({'value': time(10, 30, 15)})
assert'{"value": "10:30:15"}'==data# bytes are first base64 URL safe encoded, then decoded into UTF8 stringsdata=json.dumps({'value': b'Lorem ipsum dolor sit amet'})
assert'{"value": "TG9yZW0gaXBzdW0gZG9sb3Igc2l0IGFtZXQ="}'==data