JSON is a text format for objects, arrays, strings, numbers, booleans and null; it does not preserve every Python type.
Design a wire schema and inspect which values and type distinctions survive encoding and decoding.
A Python record contains a timestamp, a set of tags and an exact decimal amount. The dashboard expects JSON. What should each value become on the wire, and how will the receiver know what it means? The encoder needs deliberate conversion rules, not a fallback that turns everything into a string.
You'll build to_json(raw), Quarry's encoder, which crosses that gap on
purpose instead of by accident.

Ship a log record to a JSON dashboard
A dashboard that only speaks JSON needs Quarry's record turned into JSON text. The straightforward call works for plain values:
False became false, None became null, and single quotes became double
— the only kind JSON allows. The trouble starts with the types JSON has no
room for. A datetime is refused on the spot — the good kind of failure,
loud and early:
default= is the fix: dumps calls your function on anything it can't
encode and writes whatever it returns instead:
Three choices there are decisions, not formalities. sorted(value), not
list(value), because a set's iteration order isn't stable and the same data
must always produce the same text. str(value), not float(value), for
Decimal — Decimal("0.10") exists so it is not the binary approximation
of 0.1. And the hook raises at the end rather than falling back to
str(value) for everything, which would quietly turn an open file into
"<_io.TextIOWrapper ...>" in your data.
Fix this logger, which crashes on its first record:
TypeErrorRun it and read which type JSON refuses. Then teach dumps what to do with it.
Preparing this topic’s interactive investigation…
Compare today's export with yesterday's
Quarry fingerprints batches, so the same data must always produce the same text. Two dicts built in different field order are still "the same data":
sort_keys=True removes insertion order from the output. separators=(",", ":") drops the spaces, which also removes one more way two encoders could
disagree. The values that get through and shouldn't are quieter than a
refusal:
import json
print(json.dumps({"ratio": float("nan")}))json.dumps(obj, allow_nan=False) raises ValueError instead, catching the
bad value where it was made rather than in someone else's system later.
Make the wire schema explicit
If a Python Decimal("0.10") becomes the JSON string "0.10", the decimal has not magically travelled through JSON. Your encoder wrote a string, and the receiver needs a schema saying that this field represents a decimal. The same applies to an ISO timestamp: a date-shaped string remains a string until an agreed decoder validates it.
Write a three-column contract before adding a hook:
| Python value | JSON representation | Receiver's responsibility |
|---|---|---|
| timezone-aware timestamp | ISO string including offset | parse and retain/normalize timezone |
| exact monetary amount | decimal string | construct Decimal, validate scale |
| set of tags | sorted array of strings | decide whether duplicates are forbidden |
Sorting a set only works when its elements can be ordered; the lesson's tags are all strings. A generic set of mixed Python types needs a separate policy. An object_hook based only on _at is a convention for this application, not evidence that every similarly named field is a timestamp.
Test the consumer boundary: encode {"id": 7, "amount": "0.10"}, decode it, and inspect type(amount) before doing arithmetic. Then try {"id": 9007199254740993} with a consumer that represents all numbers as IEEE-754 doubles: Python's exact integer does not guarantee an exact number in every language. Large identifiers can travel as validated strings instead.
Compact separators and sorted keys stabilize output under this encoder's chosen rules. They are not a complete cross-language canonicalization standard for signatures. For strict interchange, also reject non-finite floats with allow_nan=False, decide how to reject duplicate object keys on input, and validate the decoded object's schema before using it.
Reference: JSON conversions and interoperability limits.
Bring timestamps back to life on the way in
default= works on the way out; object_hook= is its partner coming in.
loads calls it on every decoded dict, innermost first, and uses whatever it
returns:
The hook relies on a naming convention, the _at suffix, because JSON
has no timestamp-specific type. Watch the hook fire once per value it
handles, never for the ones it doesn't need to:
Quick practice
import json
hits = {404: 3, 500: 1}
back = json.loads(json.dumps(hits))
print(list(back))import json
span = (3, 9)
back = json.loads(json.dumps(span))
print(back == span, type(back).__name__)TypeErrorRun it, read which type is refused, then add a default= hook that turns a set into a sorted list.
import json
escaped = json.dumps({"city": "Zürich"})
plain = json.dumps({"city": "Zürich"}, ensure_ascii=False)
print(escaped == plain, "u" in escaped, "u" in plain)🎯 Your turn
Quarry's record stage hands the vault typed records. The starter includes
build_record(raw), a stand-in for that stage: it turns at into a
datetime, tags into a set and size into a Decimal. Write:
encode_extra(value):datetime→.isoformat(),set→sortedlist,Decimal→str, and anything else raisesTypeErrorto_json(raw):json.dumps(build_record(raw), default=encode_extra, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
Example:
to_json({"id": 1, "level": "WARN", "at": "2026-03-01T09:30:00",
"tags": ["web", "disk"], "size": "12.50"})
→ '{"at":"2026-03-01T09:30:00","id":1,"level":"WARN","size":"12.50","tags":["disk","web"]}'Hint: isinstance(value, (set, frozenset)) catches both kinds of set.
Press ▶ Run, try the Live App chips, and hit ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write pretty(record) returning the record as JSON with keys sorted and two-space indentation.
Log exporters often write JSON Lines: one JSON object per line. Write decode_lines(text) returning the list of decoded objects, skipping blank or whitespace-only lines.
Write revive_types(text). Decode text with an object_hook that turns the value of any key ending in _at into a datetime using datetime.fromisoformat, leaving it as a string if that raises ValueError. Return a dict mapping each top-level key to the type name of its decoded value, e.g. {"id": "int", "seen_at": "datetime"}.
The starter's typed(raw) turns pair into a tuple, counts into a dict with int keys, tags into a set and at into a datetime. Write roundtrip_diff(raw): build record = typed(raw), encode it with a default= hook (sets to sorted lists, datetimes to ISO strings), decode it again, and return the sorted list of keys whose decoded value is not equal to the original.
Write to_jsonl(raws). For each raw record, build it with the starter's build_record and encode it on one line exactly as the lesson's to_json does (sorted keys, compact separators, ensure_ascii=False, and default= for datetime, set and Decimal). If building a record raises ValueError (from a bad date) or decimal.InvalidOperation (from a bad size), skip it and remember its id. Return {"text": the encoded lines joined with "\n", "skipped": [ids in input order]}.
json.dumps({"ratio": float("nan")}) succeeds and prints {"ratio": NaN}, and json.loads reads it back without complaint. Explain why this is still a bug, who it hurts, and what allow_nan=False changes about where the problem shows up.