Skip to content

User friendly JSON dumps

Roberto Prevato edited this page Sep 29, 2020 · 6 revisions

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:

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
Clone this wiki locally