Skip to content

5. Python: advanced json

  • Serialize types that json does not know (datetime, Decimal, set, dataclasses) with default= or a JSONEncoder.
  • Decode into rich types: object_hook to recognize dates, parse_float=Decimal for money, object_pairs_hook to catch duplicate keys.
  • Build a reliable round trip: object → JSON → identical object.

When dumps meets a type it cannot serialize, it calls the function passed in default= and serializes whatever it returns. It is the simplest mechanism:

def converti(o):
if isinstance(o, datetime): return o.isoformat()
if isinstance(o, Decimal): return str(o) # o float(o), scegli consapevolmente
if isinstance(o, set): return sorted(o)
if is_dataclass(o): return asdict(o)
raise TypeError(f"Non so serializzare {type(o).__name__}")
json.dumps(dato, default=converti)

The alternative is a subclass of json.JSONEncoder with a default(self, o) method and cls=MioEncoder: same logic, handy when you want to reuse it in several places or encapsulate configuration.

Coming in: object_hook, object_pairs_hook, parse_float

Section titled “Coming in: object_hook, object_pairs_hook, parse_float”

loads calls object_hook(dict) for every object it decodes, from the innermost to the outermost, and uses whatever it returns. It is the place to turn ISO strings into datetime:

def riconosci_date(d):
for k, v in d.items():
if k.endswith("_at") and isinstance(v, str):
d[k] = datetime.fromisoformat(v)
return d
json.loads(testo, object_hook=riconosci_date)

object_pairs_hook, instead, receives the list of pairs (key, value) in document order: use it to reject duplicate keys or build special ordered structures. parse_float (and parse_int) replace the constructor used for numbers: parse_float=Decimal is the right way to read amounts.

“Round trip” means: loads(dumps(x)) == x. With the basic types it always works (except tuples, which come back as lists). With datetime/Decimal you must pair a default going out with a hook coming in: the convention (e.g. “every key ending in _at is an ISO date”) is yours, JSON does not know it.

curl, explained: an order with dates and amounts

Section titled “curl, explained: an order with dates and amounts”
terminal
curl -s https://corso-api-json.giuseppebosi.com/api/v1/orders/1 | jq '{created_at, total, n_righe: (.items | length)}'
/api/v1/orders/1
order 1: it has an ISO date, a decimal amount and an array of line items
jq '{…}'
builds a new object by picking fields: created_at and total as they are, n_righe computed with length on the items array
{
"created_at": "2025-01-10T21:00:00Z",
"total": 12.04,
"n_righe": 1
}

The full response:

{"id":1,"customer_id":39,"status":"delivered","shipping_address":{"street":"Via Sestri 73","city":"Bari","zip":"15399","country":"IT"},"total":12.04,"created_at":"2025-01-10T21:00:00Z","items":[{"id":1,"order_id":1,"book_id":11,"quantity":1,"unit_price":12.04}]}

created_at is a string, total a float: exactly the two cases we want to handle better.

GET/api/v1/orders/1— order 1
# pip install httpx
# python3 json_avanzato.py
import json
from dataclasses import dataclass, asdict, is_dataclass
from datetime import datetime, timezone
from decimal import Decimal
import httpx
BASE = "https://corso-api-json.giuseppebosi.com/api/v1"
# --- 1. Decodifica ricca: date vere, Decimal per gli importi ---------------------------
def riconosci_date(d: dict) -> dict:
for k, v in d.items():
if k.endswith("_at") and isinstance(v, str):
d[k] = datetime.fromisoformat(v) # accetta la 'Z' da Python 3.11
return d
testo = httpx.get(f"{BASE}/orders/1").text
ordine = json.loads(testo, object_hook=riconosci_date, parse_float=Decimal)
print(type(ordine["created_at"]).__name__, ordine["created_at"].year) # datetime 2025
print(type(ordine["total"]).__name__, ordine["total"] * 3) # Decimal 36.12
# --- 2. Codifica di tipi non nativi con default= --------------------------------------
@dataclass
class Riga:
book_id: int
quantity: int
unit_price: Decimal
def converti(o):
if isinstance(o, datetime): return o.isoformat().replace("+00:00", "Z")
if isinstance(o, Decimal): return str(o)
if isinstance(o, set): return sorted(o)
if is_dataclass(o): return asdict(o)
raise TypeError(f"Non so serializzare {type(o).__name__}")
nuovo = {
"created_at": datetime(2026, 9, 18, 9, 30, tzinfo=timezone.utc),
"total": Decimal("18.71"),
"tags": {"novità", "premio"},
"items": [Riga(7, 2, Decimal("9.355"))],
}
print(json.dumps(nuovo, default=converti, ensure_ascii=False))
# {"created_at": "2026-09-18T09:30:00Z", "total": "18.71", "tags": ["novità", "premio"],
# "items": [{"book_id": 7, "quantity": 2, "unit_price": "9.355"}]}
# --- 3. Lo stesso con una classe Encoder riusabile ------------------------------------
class Encoder(json.JSONEncoder):
def default(self, o):
return converti(o)
print(json.dumps({"q": datetime(2026, 1, 1, tzinfo=timezone.utc)}, cls=Encoder))
# --- 4. object_pairs_hook: rifiuta le chiavi duplicate --------------------------------
def senza_duplicati(coppie):
d = {}
for k, v in coppie:
if k in d:
raise ValueError(f"chiave duplicata: {k!r}")
d[k] = v
return d
try:
json.loads('{"dup": 1, "dup": 2}', object_pairs_hook=senza_duplicati)
except ValueError as e:
print(e) # chiave duplicata: 'dup'
# --- 5. Round-trip verificato ------------------------------------------------------------
def dumps(x): return json.dumps(x, default=converti, sort_keys=True)
def loads(s): return json.loads(s, object_hook=riconosci_date, parse_float=Decimal)
ritorno = loads(dumps(ordine))
print(ritorno == ordine) # False!
print(repr(ritorno["total"]), repr(ordine["total"])) # '12.04' Decimal('12.04')
# Il round-trip FALLISCE: converti ha scritto il Decimal tra apici, e in lettura è rimasto
# una stringa. Le due metà devono essere simmetriche: se in uscita scrivi un numero...
def converti_num(o):
if isinstance(o, Decimal):
return float(o) # numero JSON; la precisione torna grazie a parse_float=Decimal
return converti(o)
def dumps2(x): return json.dumps(x, default=converti_num, sort_keys=True)
andata = dumps2(ordine)
assert loads(andata) == ordine, "il round-trip ha perso qualcosa"
print("round-trip ok, byte:", len(andata))

What you should see:

datetime 2025
Decimal 36.12
{"created_at": "2026-09-18T09:30:00Z", "total": "18.71", "tags": ["novità", "premio"], "items": [{"book_id": 7, "quantity": 2, "unit_price": "9.355"}…
{"q": "2026-01-01T00:00:00Z"}
chiave duplicata: 'dup'
False
'12.04' Decimal('12.04')
round-trip ok, byte: 291

Note step 5: the first version fails because going out the Decimal becomes a string and coming in it stays one. The final assert proves that converti_num and parse_float=Decimal are symmetric: if you change the convention on one side only, the assert tells you. (float(Decimal("12.04")) is written as 12.04 and comes back as Decimal("12.04"): no loss for the two decimal places of money; with more digits, keep the string in both directions.)

Try it online, nothing to install:

Open the notebook in Google Colab

The GET request straight in your browser: https://corso-api-json.giuseppebosi.com/api/v1/orders/1

Python on Google Colab (a free Google account is needed to run the cells); TypeScript on StackBlitz (it opens and starts by itself in the browser). If the practice API is switched off, turn it on from /en/api-attiva/.

Download /api/v1/orders?limit=20. Decode with parse_float=Decimal and object_hook for the dates; then compute:

  1. the exact sum of the total values (it must be a Decimal);
  2. the most recent order (comparing datetime values, not strings);
  3. serialize the list again with default= and check that loads(dumps(lista)) == lista.
Solution
import json, httpx
from datetime import datetime
from decimal import Decimal
def hook(d):
for k, v in d.items():
if k.endswith("_at") and isinstance(v, str): d[k] = datetime.fromisoformat(v)
return d
def conv(o):
if isinstance(o, datetime): return o.isoformat().replace("+00:00", "Z")
if isinstance(o, Decimal): return float(o) # numero, non stringa: vedi punto 5
raise TypeError
testo = httpx.get("https://corso-api-json.giuseppebosi.com/api/v1/orders", params={"limit": 20}).text
ordini = json.loads(testo, object_hook=hook, parse_float=Decimal)["items"]
print(sum(o["total"] for o in ordini)) # 1334.45 (un Decimal)
print(max(ordini, key=lambda o: o["created_at"])["id"]) # 2
assert json.loads(json.dumps(ordini, default=conv), object_hook=hook, parse_float=Decimal) == ordini

What you should see:

1334.45
2

If you had written str(o) in conv, total would have come back as the string "12.04" and the assert would have failed: the outgoing and incoming conventions must match.

  • A default= that returns the object itself → infinite recursion / RecursionError.
  • datetime.fromisoformat with a trailing Z: it works from Python 3.11; before that you needed .replace("Z", "+00:00").
  • An object_hook that returns None (forgot return d): the whole object becomes None.
  • Using parse_float=Decimal and then adding with float: the imprecision comes back.

default=/JSONEncoder going out, object_hook/object_pairs_hook/parse_float coming in, and a round-trip assert as a guarantee. In the next chapter we move to JavaScript: JSON.parse and JSON.stringify with reviver, replacer and toJSON.