Skip to content

JSON

grelmicro.json

JSON serialization utilities.

Fast JSON encoding and decoding using orjson when available, with automatic fallback to the standard library json module.

orjson is roughly 7x faster than stdlib json and is included in the grelmicro[standard] extra.

Example::

from grelmicro.cache import TTLCache, JsonSerializer

cache = TTLCache(ttl=300, serializer=JsonSerializer())

JSONEncodable module-attribute

JSONEncodable: TypeAlias = (
    str
    | int
    | float
    | bool
    | datetime
    | None
    | Mapping[str, "JSONEncodable"]
    | list["JSONEncodable"]
    | tuple["JSONEncodable", ...]
)

Recursive JSON-encodable value. datetime is serialized as ISO 8601 string.

JSONDecodable module-attribute

JSONDecodable: TypeAlias = (
    dict[str, Any]
    | list[Any]
    | str
    | int
    | float
    | bool
    | None
)

Types returned by json_loads.

json_dumps_bytes

json_dumps_bytes(obj: JSONEncodable) -> bytes

Serialize object to JSON bytes using stdlib json.

json_dumps_str

json_dumps_str(obj: JSONEncodable) -> str

Serialize object to JSON string using stdlib json.

json_loads

json_loads(data: bytes | str) -> JSONDecodable

Deserialize JSON bytes or string using stdlib json.

json_default

json_default(obj: object) -> str

Handle non-serializable types for stdlib json.

Converts datetime instances to ISO 8601 strings. Raises TypeError for all other non-serializable types.

has_orjson

has_orjson() -> bool

Check if orjson is available.