Salta ai contenuti

4. Python: json base

  • Usare le quattro funzioni del modulo json: loads/dumps per le stringhe, load/dump per i file.
  • Controllare l’output: indentazione, ordine delle chiavi, caratteri non ASCII, compattezza.
  • Sapere esattamente in cosa si trasforma ogni tipo JSON in Python e viceversa.
  • Gestire JSONDecodeError leggendo dove è l’errore.

Il modulo json è nella libreria standard: niente da installare. Le funzioni finiscono in s quando lavorano su stringhe:

Funzione Da A
json.loads(testo) str (o bytes) JSON oggetto Python
json.dumps(oggetto) oggetto Python str JSON
json.load(file) file aperto in lettura oggetto Python
json.dump(oggetto, file) oggetto Python scrive sul file

Decodifica (loads):

JSON Python
oggetto dict
array list
stringa str
numero intero int (precisione arbitraria)
numero con . o esponente float
true / false True / False
null None

Codifica (dumps) accetta in più tuple (→ array) e, per le chiavi, int/float/bool/None (→ convertite in stringa). Tutto il resto — datetime, Decimal, set, dataclass, oggetti tuoi — solleva TypeError: Object of type X is not JSON serializable. Il capitolo 5 spiega come estendere.

json.dumps(obj,
indent=2, # None = compatto su una riga; 2 o 4 = leggibile
sort_keys=True, # chiavi in ordine alfabetico: output stabile per diff e hash
ensure_ascii=False, # True (default) scrive "caff\u00e8"; False scrive "caffè"
separators=(",", ":"), # il più compatto possibile (default con indent=None è (", ", ": "))
default=…, # funzione chiamata per i tipi sconosciuti (capitolo 5)
)

Sottoclasse di ValueError con tre attributi utili: msg, pos (indice del carattere), lineno/colno. Intercettala sempre quando il JSON arriva dall’esterno.

curl, spiegato: la stessa richiesta che faremo in Python

Sezione intitolata “curl, spiegato: la stessa richiesta che faremo in Python”

Prendiamo i primi due libri, con la query string che limita i risultati:

terminale
curl -s 'https://corso-api-json.giuseppebosi.com/api/v1/books?limit=2' -o libri.json
python3 -m json.tool libri.json | head -20
'…?limit=2'
dopo ? inizia la query string: parametri chiave=valore separati da &. Gli apici proteggono ? e & dalla shell
-o libri.json
output: salva il corpo della risposta nel file invece di stamparlo
python3 -m json.tool libri.json
rilegge il file, lo valida e lo stampa indentato
| head -20
solo le prime 20 righe
{
"items": [
{
"id": 1,
"title": "Il silenzio di Ustica",
"isbn": "978-88-81482-001-1",
"author_id": 19,
"category_id": 2,
"price": 18.71,
"pages": 120,
"published_year": 2002,
"language": "it",
"in_stock": true,
"attributes": {
"format": "brossura",
"cover": "morbida",
"awards": [],
"dimensions_cm": {
"w": 15,
"h": 19
},

La risposta di una lista è una “busta”: items (array), meta (paginazione) e links (pagina successiva/precedente). La vedremo a fondo nella Sezione 2.

GET/api/v1/books?limit=2— la busta di una lista: items, meta, links
# pip install httpx
# python3 json_base.py
import json
import httpx
BASE = "https://corso-api-json.giuseppebosi.com/api/v1"
# 1. Dalla rete: httpx fa json.loads per te
r = httpx.get(f"{BASE}/books", params={"limit": 2})
dati = r.json()
print(type(dati), list(dati)) # <class 'dict'> ['items', 'meta', 'links']
print(dati["meta"]) # {'page': 1, 'limit': 2, 'total': 80, 'pages': 40}
# 2. Lo stesso a mano: testo -> oggetto
testo = r.text
dati2 = json.loads(testo)
assert dati == dati2
# 3. Oggetto -> testo, in tre stili
primo = dati["items"][0]
print(json.dumps(primo)) # compatto, ASCII, ordine originale
print(json.dumps(primo, indent=2, ensure_ascii=False)) # leggibile
print(json.dumps(primo, sort_keys=True, separators=(",", ":"))) # minimo e stabile
# 4. File: dump / load
with open("libri.json", "w", encoding="utf-8") as f:
json.dump(dati["items"], f, indent=2, ensure_ascii=False)
with open("libri.json", encoding="utf-8") as f:
riletti = json.load(f)
print(len(riletti), riletti[1]["title"]) # 2 TypeScript e Ferrara
# 5. Tipi: cosa esce da loads
for chiave in ("id", "price", "in_stock", "avg_rating", "attributes", "title"):
print(f"{chiave:12} {type(primo[chiave]).__name__}")
# id int / price float / in_stock bool / avg_rating NoneType / attributes dict / title str
# 6. Errori
try:
json.loads('{"id": 7,}')
except json.JSONDecodeError as e:
print(e.msg, "| pos:", e.pos, "| riga:", e.lineno, "colonna:", e.colno)
# Expecting property name enclosed in double quotes | pos: 9 | riga: 1 colonna: 10

Cosa dovresti vedere:

<class 'dict'> ['items', 'meta', 'links']
{'page': 1, 'limit': 2, 'total': 80, 'pages': 40}
{"id": 1, "title": "Il silenzio di Ustica", "isbn": "978-88-81482-001-1", "author_id": 19, "category_id": 2, "price": 18.71, "pages": 120, "published…
{
"id": 1,
"title": "Il silenzio di Ustica",
"isbn": "978-88-81482-001-1",
"author_id": 19,
"category_id": 2,
"price": 18.71,
"pages": 120,
"published_year": 2002,
"language": "it",
"in_stock": true,
"attributes": {
"format": "brossura",
"cover": "morbida",
…

Provalo online, senza installare nulla:

Apri il notebook in Google Colab

La richiesta GET diretta nel browser: https://corso-api-json.giuseppebosi.com/api/v1/books?limit=2

Python su Google Colab (serve un account Google gratuito per eseguire le celle); TypeScript su StackBlitz (si apre e parte da solo nel browser). Se l’API di prova è spenta, accendila da /api-attiva/.

Scarica /api/v1/books?limit=100 e scrivi uno script che:

  1. salva in catalogo.json solo i campi id, title, price di ogni libro, indentato e con le chiavi ordinate;
  2. rilegge il file e stampa il titolo del libro più caro;
  3. prova a fare json.dumps del valore {"quando": datetime.now()} e stampa il messaggio dell’eccezione.
Soluzione
import json
from datetime import datetime
import httpx
libri = httpx.get("https://corso-api-json.giuseppebosi.com/api/v1/books", params={"limit": 100}).json()["items"]
ridotti = [{"id": b["id"], "title": b["title"], "price": b["price"]} for b in libri]
with open("catalogo.json", "w", encoding="utf-8") as f:
json.dump(ridotti, f, indent=2, sort_keys=True, ensure_ascii=False)
with open("catalogo.json", encoding="utf-8") as f:
riletti = json.load(f)
print(max(riletti, key=lambda b: b["price"])["title"]) # Quello che resta di Sestri
try:
json.dumps({"quando": datetime.now()})
except TypeError as e:
print(e) # Object of type datetime is not JSON serializable

Cosa dovresti vedere:

Quello che resta di Sestri
Object of type datetime is not JSON serializable
  • json.load(testo) con una stringa: load vuole un file; per le stringhe è loads.
  • Dimenticare encoding="utf-8" in open(): su Windows il default può essere cp1252 e i caratteri accentati si corrompono.
  • Confrontare JSON come stringhe: '{"a":1,"b":2}' != '{"b":2,"a":1}' anche se rappresentano lo stesso oggetto. Confronta gli oggetti, o serializza con sort_keys=True.
  • Usare eval() per “parsare” JSON. Mai: esegue codice arbitrario.

loads/dumps per le stringhe, load/dump per i file, indent/sort_keys/ensure_ascii per controllare l’output, JSONDecodeError per gli errori. I tipi si mappano in modo prevedibile; ciò che non si mappa (date, Decimal, oggetti) è l’argomento del prossimo capitolo.