Base di conoscenzaCentro esami
ITItaliano
Scegli la lingua13

CKTIS / Python

Ingresso, uscita e serializzazione

Distingue i byte del flusso, la codifica e il formato analizzato a partire dal testo.

Versione: Python 3.14; repository image, production runtime not attested

Sintassi

json.loads(raw.decode("utf-8"))

Distingue i byte del flusso, la codifica e il formato analizzato a partire dal testo.

UTF-8 non valido solleva UnicodeDecodeError prima dell’analisi JSON e testo JSON malformato solleva JSONDecodeError. Il letterale JSON null valido diventa None.

L’esempio distingue entrambi gli errori e i dati validi.

Esempi

import io
import json

def decode(raw):
    text = io.BytesIO(raw).read().decode("utf-8")
    return json.loads(text)
for raw in (b"null", b'{"n":2}', b"{", bytes([255])):
    try:
        print(repr(decode(raw)))
    except (UnicodeDecodeError, json.JSONDecodeError) as error:
        print(type(error).__name__)
stream = io.BytesIO()
payload = {"word": "été"}
stream.write(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
stream.seek(0)
print(decode(stream.read()) == payload)

Risultato

None
{'n': 2}
JSONDecodeError
UnicodeDecodeError
True

L’esempio distingue entrambi gli errori e i dati validi.

Fonti