Skip to content

Commit

Permalink
Merge branch 'trs/json-serialize-dates'
Browse files Browse the repository at this point in the history
  • Loading branch information
tsibley committed Jul 18, 2024
2 parents e9850e9 + e20f920 commit 556aa28
Showing 1 changed file with 18 additions and 2 deletions.
20 changes: 18 additions & 2 deletions augur/io/json.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,14 +32,29 @@
SOFTWARE.
"""
import json
from datetime import datetime
from datetime import date, datetime
from typing import Iterable
from uuid import UUID


def as_json(value):
"""
Converts *value* to a JSON string using our custom :class:`JsonEncoder`.
The custom encoder supports serialization of :class:`~datetime.date` objects:
>>> as_json(date(year=2024, month=7, day=17))
'"2024-07-17"'
:class:`~datetime.datetime` objects:
>>> as_json(datetime(year=2024, month=7, day=17, hour=11, minute=38))
'"2024-07-17T11:38:00"'
and :class:`~uuid.UUID` objects:
>>> as_json(UUID(int=147952133113722764103424939352979237618))
'"6f4e8b5a-8500-4928-b7ae-dc098a256af2"'
"""
return json.dumps(value, allow_nan = False, cls = JsonEncoder)

Expand Down Expand Up @@ -96,10 +111,11 @@ def default(self, value):
"""
Returns *value* as JSON or raises a TypeError.
Serializes:
* :class:`~datetime.date` using :meth:`~datetime.date.isoformat()`
* :class:`~datetime.datetime` using :meth:`~datetime.datetime.isoformat()`
* :class:`~uuid.UUID` using ``str()``
"""
if isinstance(value, datetime):
if isinstance(value, (date, datetime)):
return value.isoformat()

elif isinstance(value, UUID):
Expand Down

0 comments on commit 556aa28

Please sign in to comment.