Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Input, output and serialization

Separate the stream’s bytes, their character encoding and the format parsed from the resulting text.

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

Syntax

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

Separate the stream’s bytes, their character encoding and the format parsed from the resulting text.

UTF-8 decoding can fail before JSON parsing begins, and malformed JSON text raises JSONDecodeError. A successfully parsed JSON null instead returns None.

The example reads byte streams and reports each of these distinct outcomes.

Examples

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)

Result

None
{'n': 2}
JSONDecodeError
UnicodeDecodeError
True

The example reads byte streams and reports each of these distinct outcomes.

Sources