Serialization and Deserialization · Practice
Quiz & exercises
Answer each question to see the explanation. Your best score is saved in this browser.
Quiz
Coding exercises
Write your code, then press Check (or Shift+Enter) to run the tests. Drafts are saved as you type.
Exercise 1: A strict default function ✓ Passed
Write a function to_json(arg) to use as the default= argument of json.dumps. It must convert:
- datetime and date objects to their ISO format string (isoformat()), - Decimal objects to strings, e.g. Decimal('9.99') → '9.99', - set and frozenset objects to a sorted list,
and raise a TypeError for anything else, so unsupported values are never silently written as null.
import json
from datetime import date, datetime
from decimal import Decimal
def to_json(arg):
# your code here
pass
def test_datetime():
"""datetime becomes an ISO string"""
s = json.dumps({'t': datetime(2024, 3, 15, 9, 30)}, default=to_json)
assert s == '{"t": "2024-03-15T09:30:00"}', s
def test_date():
"""date becomes an ISO string"""
s = json.dumps([date(1939, 10, 27)], default=to_json)
assert s == '["1939-10-27"]', s
def test_decimal():
"""Decimal becomes a string, keeping trailing zeros"""
s = json.dumps({'p': Decimal('337.60')}, default=to_json)
assert s == '{"p": "337.60"}', s
def test_sets():
"""sets and frozensets become sorted lists"""
s = json.dumps({'a': {3, 1, 2}, 'b': frozenset('cab')}, default=to_json)
assert s == '{"a": [1, 2, 3], "b": ["a", "b", "c"]}', s
def test_nested():
"""works anywhere in a nested structure"""
s = json.dumps({'x': [{'d': date(2020, 1, 1)}]}, default=to_json)
assert s == '{"x": [{"d": "2020-01-01"}]}', s
def test_unknown_raises():
"""unsupported types raise TypeError"""
try:
json.dumps({'c': 1 + 2j}, default=to_json)
except TypeError:
pass
else:
raise AssertionError('complex numbers should raise TypeError')
Hints (2)
datetimeis a subclass ofdate, and both haveisoformat(), so one check can cover both.- If none of your checks match,
raise TypeError(...)instead of falling off the end of the function (which returnsNone).
Show a solution
import json
from datetime import date, datetime
from decimal import Decimal
def to_json(arg):
if isinstance(arg, (date, datetime)):
return arg.isoformat()
if isinstance(arg, Decimal):
return str(arg)
if isinstance(arg, (set, frozenset)):
return sorted(arg)
raise TypeError(f'Object of type {type(arg).__name__} is not JSON serializable')Exercise 2: Decoding tagged values ✓ Passed
A service encodes special values as JSON objects with a "__type__" key:
- {"__type__": "fraction", "numerator": 1, "denominator": 3} means Fraction(1, 3) - {"__type__": "complex", "real": 1.0, "imag": -2.0} means complex(1.0, -2.0) - {"__type__": "date", "value": "2024-03-15"} means date(2024, 3, 15)
Write decode_hook(obj) for use as object_hook, and load(text) that calls json.loads with it. Any other object (including ones with an unknown __type__) must be returned unchanged.
import json
from datetime import date
from fractions import Fraction
def decode_hook(obj):
# your code here
return obj
def load(text):
return json.loads(text)
def test_fraction():
"""fractions are decoded"""
r = load('{"x": {"__type__": "fraction", "numerator": 1, "denominator": 3}}')
assert r == {'x': Fraction(1, 3)}, r
def test_complex():
"""complex numbers are decoded"""
r = load('[{"__type__": "complex", "real": 1.0, "imag": -2.0}]')
assert r == [1 - 2j], r
def test_date():
"""dates are decoded"""
r = load('{"d": {"__type__": "date", "value": "2024-03-15"}}')
assert r['d'] == date(2024, 3, 15) and type(r['d']) is date, r
def test_nested():
"""tagged values are found at any depth"""
r = load('{"a": {"b": [{"c": {"__type__": "fraction", "numerator": 2, "denominator": 4}}]}}')
assert r == {'a': {'b': [{'c': Fraction(1, 2)}]}}, r
def test_plain_unchanged():
"""ordinary objects and unknown tags are left alone"""
r = load('{"p": {"x": 1}, "q": {"__type__": "mystery", "v": 1}}')
assert r == {'p': {'x': 1}, 'q': {'__type__': 'mystery', 'v': 1}}, r
Hints (3)
object_hookis called for every JSON object, innermost first, so nesting takes care of itself.- Use
obj.get('__type__')so dictionaries without the key don't raiseKeyError. - Don't forget to pass
object_hook=decode_hooktojson.loads.
Show a solution
import json
from datetime import date
from fractions import Fraction
def decode_hook(obj):
match obj.get('__type__'):
case 'fraction':
return Fraction(obj['numerator'], obj['denominator'])
case 'complex':
return complex(obj['real'], obj['imag'])
case 'date':
return date.fromisoformat(obj['value'])
case _:
return obj
def load(text):
return json.loads(text, object_hook=decode_hook)Exercise 3: An allow-list for unpickling ✓ Passed
Write safe_loads(data) that unpickles data (bytes) like pickle.loads, but only allows these globals:
- datetime.date, datetime.datetime - decimal.Decimal - collections.OrderedDict
Any other global must raise pickle.UnpicklingError. Built-in containers and scalars (lists, dicts, sets, strings, numbers) must still load normally.
Subclass pickle.Unpickler and override find_class(self, module, name).
import io
import pickle
def safe_loads(data):
return pickle.loads(data)
import os
from collections import OrderedDict, Counter
from datetime import date, datetime
from decimal import Decimal
class Evil:
def __reduce__(self):
return (os.getcwd, ())
def test_plain_data():
"""plain built-in data loads"""
obj = [1, 'two', {3: (4.0, None)}, {5, 6}]
assert safe_loads(pickle.dumps(obj)) == obj
def test_allowed_classes():
"""allow-listed classes load"""
obj = {'d': date(2024, 1, 2), 't': datetime(2024, 1, 2, 3, 4), 'p': Decimal('9.99'),
'o': OrderedDict(a=1)}
assert safe_loads(pickle.dumps(obj)) == obj
def test_blocks_function_call():
"""a payload that calls os.getcwd is refused"""
try:
safe_loads(pickle.dumps(Evil()))
except pickle.UnpicklingError:
pass
else:
raise AssertionError('os.getcwd was allowed')
def test_blocks_other_classes():
"""classes not on the list are refused"""
try:
safe_loads(pickle.dumps(Counter('abc')))
except pickle.UnpicklingError:
pass
else:
raise AssertionError('collections.Counter was allowed')
Hints (3)
pickle.Unpicklerreads from a binary file object; wrap the bytes inio.BytesIO(data)and call.load().find_classmust return the actual object:getattr(importlib.import_module(module), name).- Built-in data types have their own opcodes and never reach
find_class, so you don't need to allow them.
Show a solution
import importlib
import io
import pickle
ALLOWED = {
('datetime', 'date'),
('datetime', 'datetime'),
('decimal', 'Decimal'),
('collections', 'OrderedDict'),
}
class SafeUnpickler(pickle.Unpickler):
def find_class(self, module, name):
if (module, name) in ALLOWED:
return getattr(importlib.import_module(module), name)
raise pickle.UnpicklingError(f'global {module}.{name} is forbidden')
def safe_loads(data):
return SafeUnpickler(io.BytesIO(data)).load()Exercise 4: Load and validate a YAML config ✓ Passed
Write load_config(text) that:
1. parses the YAML text safely (no Python object tags allowed), 2. validates the result against CONFIG_SCHEMA (given) with jsonschema, 3. returns the config dict with defaults filled in: debug defaults to False and workers to 1.
If the YAML can't be parsed, or the data doesn't match the schema, raise ValueError (with any message).
import yaml
import jsonschema
CONFIG_SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"debug": {"type": "boolean"},
"workers": {"type": "integer", "minimum": 1},
"hosts": {"type": "array", "items": {"type": "string"}, "minItems": 1},
},
"required": ["name", "hosts"],
"additionalProperties": False,
}
def load_config(text):
return yaml.load(text, Loader=yaml.UnsafeLoader)
def raises_value_error(text):
try:
load_config(text)
except ValueError:
return True
return False
def test_valid_with_defaults():
"""a minimal config gets its defaults"""
cfg = load_config('name: api\nhosts:\n - a.example\n - b.example\n')
assert cfg == {'name': 'api', 'hosts': ['a.example', 'b.example'],
'debug': False, 'workers': 1}, cfg
def test_explicit_values_kept():
"""given values override the defaults"""
cfg = load_config('name: api\nhosts: [x]\ndebug: true\nworkers: 4\n')
assert cfg['debug'] is True and cfg['workers'] == 4, cfg
def test_schema_violation():
"""invalid data raises ValueError"""
assert raises_value_error('name: api\nhosts: [x]\nworkers: 0\n'), 'workers: 0 accepted'
assert raises_value_error('name: api\n'), 'missing hosts accepted'
assert raises_value_error('name: api\nhosts: [x]\nport: 80\n'), 'unknown key accepted'
def test_bad_yaml():
"""unparseable YAML raises ValueError"""
assert raises_value_error('name: [unclosed\n'), 'broken YAML accepted'
def test_no_python_tags():
"""Python object tags are refused"""
assert raises_value_error('name: !!python/object/apply:os.getcwd []\nhosts: [x]\n'), \
'python/object/apply tag was executed'
Hints (3)
yaml.safe_loadrefuses Python tags by raising ayaml.YAMLErrorsubclass, just like it does for malformed YAML.jsonschema.validate(data, schema)raisesjsonschema.ValidationError; catch it and raiseValueErrorinstead.{**DEFAULTS, **data}merges the two dicts, with values fromdatawinning.
Show a solution
import yaml
import jsonschema
CONFIG_SCHEMA = {
"type": "object",
"properties": {
"name": {"type": "string", "minLength": 1},
"debug": {"type": "boolean"},
"workers": {"type": "integer", "minimum": 1},
"hosts": {"type": "array", "items": {"type": "string"}, "minItems": 1},
},
"required": ["name", "hosts"],
"additionalProperties": False,
}
DEFAULTS = {'debug': False, 'workers': 1}
def load_config(text):
try:
data = yaml.safe_load(text)
except yaml.YAMLError as ex:
raise ValueError(f'invalid YAML: {ex}') from ex
try:
jsonschema.validate(data, CONFIG_SCHEMA)
except jsonschema.ValidationError as ex:
raise ValueError(f'invalid config: {ex.message}') from ex
return {**DEFAULTS, **data}