18.4. JSON Encoder
Problem with
date
,datetime
,time
,timedelta
Exception during encoding datetime
Encoder will be used, when standard procedure fails
18.4.1. SetUp
>>> from datetime import datetime, date, time, timedelta
>>> import json
18.4.2. Problem
>>> DATA = {
... 'firstname': 'Mark',
... 'lastname': 'Watney',
... 'birthdate': date(1994, 10, 12)
... }
>>>
>>> result = json.dumps(DATA)
Traceback (most recent call last):
TypeError: Object of type date is not JSON serializable
18.4.3. Default Function with Lambda
>>> DATA = {
... 'firstname': 'Mark',
... 'lastname': 'Watney',
... 'birthdate': date(1994, 10, 12)
... }
>>>
>>> result = json.dumps(DATA, default=lambda x: x.isoformat(), indent=2)
>>> print(result)
{
"firstname": "Mark",
"lastname": "Watney",
"birthdate": "1994-10-12"
}
18.4.4. Default Function with If
>>> DATA = {
... 'firstname': 'Mark',
... 'lastname': 'Watney',
... 'birthdate': date(1994, 10, 12)
... }
>>>
>>>
>>> def encoder(x):
... if type(x) is date:
... return x.isoformat()
>>>
>>>
>>> result = json.dumps(DATA, default=encoder, indent=2)
>>> print(result)
{
"firstname": "Mark",
"lastname": "Watney",
"birthdate": "1994-10-12"
}
18.4.5. Default Function with Match
>>> DATA = {
... 'firstname': 'Mark',
... 'lastname': 'Watney',
... 'birthdate': date(1994, 10, 12)
... }
>>>
>>>
>>> def encoder(x):
... match x:
... case datetime() | date() | time():
... return x.isoformat()
... case timedelta():
... return x.total_seconds()
>>>
>>>
>>> result = json.dumps(DATA, default=encoder, indent=2)
>>> print(result)
{
"firstname": "Mark",
"lastname": "Watney",
"birthdate": "1994-10-12"
}
18.4.6. Monkey Patching with Lambda Expression
>>> DATA = {
... 'firstname': 'Mark',
... 'lastname': 'Watney',
... 'birthdate': date(1994, 10, 12)
... }
>>>
>>> json.JSONEncoder.default = lambda self,x: x.isoformat()
>>>
>>> result = json.dumps(DATA, indent=2)
>>> print(result)
{
"firstname": "Mark",
"lastname": "Watney",
"birthdate": "1994-10-12"
}
18.4.7. Dependency Injection
>>> DATA = {
... 'firstname': 'Mark',
... 'lastname': 'Watney',
... 'birthdate': date(1994, 10, 12)
... }
>>>
>>>
>>> class Encoder(json.JSONEncoder):
... def default(self, x):
... if type(x) is date:
... return x.isoformat()
>>>
>>>
>>> result = json.dumps(DATA, cls=Encoder, indent=2)
>>> print(result)
{
"firstname": "Mark",
"lastname": "Watney",
"birthdate": "1994-10-12"
}
18.4.8. Use Case - 1
>>> from datetime import datetime, date, time, timedelta
>>> import json
>>>
>>>
>>> DATA = {
... 'name': 'Mark Watney',
... 'birthdate': date(1994, 10, 12),
... 'launch': datetime(1969, 7, 21, 2, 56, 15),
... 'landing': time(12, 30),
... 'duration': timedelta(days=13),
... }
>>>
>>>
>>> class Encoder(json.JSONEncoder):
... def default(self, value):
... if type(value) in (datetime, date, time):
... return value.isoformat()
... if type(value) is timedelta:
... return value.total_seconds()
>>>
>>>
>>> result = json.dumps(DATA, cls=Encoder, indent=2)
>>> print(result)
{
"name": "Mark Watney",
"birthdate": "1994-10-12",
"launch": "1969-07-21T02:56:15",
"landing": "12:30:00",
"duration": 1123200.0
}
18.4.9. Use Case - 2
>>> from datetime import datetime, date, time, timedelta
>>> import json
>>>
>>>
>>> DATA = {
... 'name': 'Mark Watney',
... 'birthdate': date(1994, 10, 12),
... 'launch': datetime(1969, 7, 21, 2, 56, 15),
... 'landing': time(12, 30),
... 'duration': timedelta(days=13),
... }
>>>
>>>
>>> def encoder(x):
... match x:
... case datetime() | date() | time():
... return x.isoformat()
... case timedelta():
... return x.total_seconds()
>>>
>>>
>>> result = json.dumps(DATA, default=encoder, indent=2)
>>> print(result)
{
"name": "Mark Watney",
"birthdate": "1994-10-12",
"launch": "1969-07-21T02:56:15",
"landing": "12:30:00",
"duration": 1123200.0
}
18.4.10. Assignments
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: JSON Encoder Function
# - Difficulty: easy
# - Lines: 4
# - Minutes: 5
# %% English
# 1. Define `result: str` with JSON encoded `DATA`
# 2. Use encoder function
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: str` z zakodowanym `DATA` w JSON
# 2. Użyj enkodera funkcyjnego
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `json.dumps(default=...)`
# - `isinstance(obj, date|datetime)`
# - `date.toisoformat()`
# - `datetime.toisoformat()`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isfunction
>>> assert isfunction(encoder), \
'Encoder must be a function'
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> print(result) # doctest: +NORMALIZE_WHITESPACE
{"mission": "Ares 3",
"launch_date": "2035-06-29T00:00:00",
"destination": "Mars",
"destination_landing": "2035-11-07T00:00:00",
"destination_location": "Acidalia Planitia",
"crew": [{"name": "Melissa Lewis", "birthdate": "1995-07-15"},
{"name": "Rick Martinez", "birthdate": "1996-01-21"},
{"name": "Alex Vogel", "birthdate": "1994-11-15"},
{"name": "Chris Beck", "birthdate": "1999-08-02"},
{"name": "Beth Johanssen", "birthdate": "2006-05-09"},
{"name": "Mark Watney", "birthdate": "1994-10-12"}]}
"""
import json
from datetime import date, datetime
from typing import Any
DATA = {
'mission': 'Ares 3',
'launch_date': datetime(2035, 6, 29),
'destination': 'Mars',
'destination_landing': datetime(2035, 11, 7),
'destination_location': 'Acidalia Planitia',
'crew': [
{'name': 'Melissa Lewis', 'birthdate': date(1995, 7, 15)},
{'name': 'Rick Martinez', 'birthdate': date(1996, 1, 21)},
{'name': 'Alex Vogel', 'birthdate': date(1994, 11, 15)},
{'name': 'Chris Beck', 'birthdate': date(1999, 8, 2)},
{'name': 'Beth Johanssen', 'birthdate': date(2006, 5, 9)},
{'name': 'Mark Watney', 'birthdate': date(1994, 10, 12)}]}
# JSON encoder
def encoder(obj):
...
# JSON encoded DATA
# type: str
result = ...
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% About
# - Name: JSON Encoder Class
# - Difficulty: easy
# - Lines: 6
# - Minutes: 5
# %% English
# 1. Define `result: str` with JSON encoded `DATA`
# 2. Use encoder class
# 3. Run doctests - all must succeed
# %% Polish
# 1. Zdefiniuj `result: str` z zakodowanym `DATA` w JSON
# 2. Użyj enkodera klasowego
# 3. Uruchom doctesty - wszystkie muszą się powieść
# %% Hints
# - `json.dumps(default=...)`
# - `isinstance(obj, date|datetime)`
# - `date.toisoformat()`
# - `datetime.toisoformat()`
# %% Tests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isclass
>>> assert isclass(Encoder), \
'Encoder must be a class'
>>> assert issubclass(Encoder, json.JSONEncoder), \
'Encoder must inherit from `json.JSONEncoder`'
>>> assert result is not Ellipsis, \
'Assign result to variable: `result`'
>>> assert type(result) is str, \
'Variable `result` has invalid type, should be str'
>>> print(result) # doctest: +NORMALIZE_WHITESPACE
{"mission": "Ares 3",
"launch_date": "2035-06-29T00:00:00",
"destination": "Mars",
"destination_landing": "2035-11-07T00:00:00",
"destination_location": "Acidalia Planitia",
"crew": [{"name": "Melissa Lewis", "birthdate": "1995-07-15"},
{"name": "Rick Martinez", "birthdate": "1996-01-21"},
{"name": "Alex Vogel", "birthdate": "1994-11-15"},
{"name": "Chris Beck", "birthdate": "1999-08-02"},
{"name": "Beth Johanssen", "birthdate": "2006-05-09"},
{"name": "Mark Watney", "birthdate": "1994-10-12"}]}
"""
import json
from datetime import date, datetime
DATA = {
'mission': 'Ares 3',
'launch_date': datetime(2035, 6, 29),
'destination': 'Mars',
'destination_landing': datetime(2035, 11, 7),
'destination_location': 'Acidalia Planitia',
'crew': [
{'name': 'Melissa Lewis', 'birthdate': date(1995, 7, 15)},
{'name': 'Rick Martinez', 'birthdate': date(1996, 1, 21)},
{'name': 'Alex Vogel', 'birthdate': date(1994, 11, 15)},
{'name': 'Chris Beck', 'birthdate': date(1999, 8, 2)},
{'name': 'Beth Johanssen', 'birthdate': date(2006, 5, 9)},
{'name': 'Mark Watney', 'birthdate': date(1994, 10, 12)}]}
# JSON encoder
class Encoder:
...
# JSON encoded DATA
# type: str
result = ...