Serialization and Deserialization · Practice

Quiz & exercises

Answer each question to see the explanation. Your best score is saved in this browser.

Quiz

1. Why should you never call pickle.loads on data received from an untrusted source?
2. What does this print?
import pickle

inner = {'a': 1}
outer = {'x': inner, 'y': inner}
copy = pickle.loads(pickle.dumps(outer))
print(copy['x'] is copy['y'], copy['x'] is inner)
3. What does this print?
import json

d = {1: (10, 20)}
print(json.loads(json.dumps(d)))
4. What does this print?
import json

def fmt(obj):
    if isinstance(obj, set):
        return sorted(obj)

print(json.dumps({'s': {3, 1}, 'c': 1j}, default=fmt))
5. What does this print?
import json

calls = []
def default(obj):
    calls.append(obj)
    return str(obj)

json.dumps({'name': 'Python', 'n': (1, 2)}, default=default)
print(len(calls))
6. In a JSONEncoder subclass, which method do you override to support new types, and what should it do with types it doesn't support?
7. In which order does object_hook receive the objects of {"a": {"b": {"c": 1}}}?
8. What does this print?
import json
from decimal import Decimal

d = json.loads('{"a": 0.1, "b": 0.2, "n": 3}', parse_float=Decimal)
print(d['a'] + d['b'], type(d['n']).__name__)
9. What does loads return when you override decode in a JSONDecoder subclass and pass it as cls?
10. This document is checked with jsonschema.validate. What happens?
schema = {
    "type": "object",
    "properties": {"age": {"type": "integer", "minimum": 0}},
}
instance = {"name": "John"}
11. What does this print?
import yaml

print(yaml.safe_load('country: NO\nversion: 3.10\nzip: "02134"'))
12. Which statement about marshmallow and serpy is correct?

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

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.

Hints (2)
  1. datetime is a subclass of date, and both have isoformat(), so one check can cover both.
  2. If none of your checks match, raise TypeError(...) instead of falling off the end of the function (which returns None).
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

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.

Hints (3)
  1. object_hook is called for every JSON object, innermost first, so nesting takes care of itself.
  2. Use obj.get('__type__') so dictionaries without the key don't raise KeyError.
  3. Don't forget to pass object_hook=decode_hook to json.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

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).

Hints (3)
  1. pickle.Unpickler reads from a binary file object; wrap the bytes in io.BytesIO(data) and call .load().
  2. find_class must return the actual object: getattr(importlib.import_module(module), name).
  3. 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

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).

Hints (3)
  1. yaml.safe_load refuses Python tags by raising a yaml.YAMLError subclass, just like it does for malformed YAML.
  2. jsonschema.validate(data, schema) raises jsonschema.ValidationError; catch it and raise ValueError instead.
  3. {**DEFAULTS, **data} merges the two dicts, with values from data winning.
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}