Skip to content

json_utils

Lightweight JSON helpers with optional orjson acceleration.

dumps_json

dumps_json(data, *, indent=False)

Serialize Python data to JSON bytes, preferring orjson when available.

Source code in src/services/cache/json_utils.py
def dumps_json(data: Any, *, indent: bool = False) -> bytes:
    """Serialize Python data to JSON bytes, preferring orjson when available."""
    if _ORJSON is not None:
        orjson_mod = cast(Any, _ORJSON)
        option = orjson_mod.OPT_INDENT_2 if indent else 0
        return cast(bytes, orjson_mod.dumps(data, option=option))

    kwargs: dict[str, Any] = {"ensure_ascii": False}
    if indent:
        kwargs["indent"] = 2
    return json.dumps(data, **kwargs).encode()

loads_json

loads_json(data)

Deserialize JSON bytes into Python data.

Source code in src/services/cache/json_utils.py
def loads_json(data: bytes) -> Any:
    """Deserialize JSON bytes into Python data."""
    if _ORJSON is not None:
        orjson_mod = cast(Any, _ORJSON)
        return orjson_mod.loads(data)
    return json.loads(data.decode())