Skip to content

JSON Handler

For json loads and dumps you have the option to use the json module from the standard library, or orjson. This done by setting the json_handler when creating the AsyncClient or Client. By default the standard library json module will be used. The examples below use Client, and the same options are available for AsyncClient.

Standard Library json Module

Custom Serializer

In some cases your documents will contain types that the Python JSON serializer does not know how to handle. When this happens you can provide your own custom serializer when using the json module.

Example

from datetime import datetime
from json import JSONEncoder
from uuid import uuid4

from meilisearch_python_sdk import Client
from meilisearch_python_sdk.json_handler import BuiltinHandler


class CustomEncoder(JSONEncoder):
    def default(self, o):
        if isinstance(o, (UUID, datetime)):
            return str(o)

        # Let the base class default method raise the TypeError
        return super().default(o)


documents = [
    {"id": uuid4(), "title": "test 1", "when": datetime.now()},
    {"id": uuid4(), "title": "Test 2", "when": datetime.now()},
]
with Client("http://127.0.0.1:7700", json_handler=BuiltinHandler(serializer=CustomEncoder)) as client:
    index = client.index("movies", primary_key="id")
    index.add_documents(documents)

orjson

Note that if orjson is installed and no json_handler is secified, orjson is used as the handler by default.

Example

from uuid import uuid4

from meilisearch_python_sdk import Client
from meilisearch_python_sdk.json_handler import OrjsonHandler


documents = [
    {"id": uuid4(), "title": "test 1"},
    {"id": uuid4(), "title": "Test 2"},
]
with Client("http://127.0.0.1:7700", json_handler=OrjsonHandler()) as client:
    index = client.index("movies", primary_key="id")
    index.add_documents(documents)

JSON Handler API

meilisearch_python_sdk.json_handler

BuiltinHandler

Bases: _JsonHandler

Source code in meilisearch_python_sdk/json_handler.py
class BuiltinHandler(_JsonHandler):
    serializer: type[json.JSONEncoder] | None = None

    def __init__(self, serializer: type[json.JSONEncoder] | None = None) -> None:
        """Uses the json module from the Python standard library.

        Args:
            serializer: A custom JSONEncode to handle serializing fields that the build in
                json.dumps cannot handle, for example UUID and datetime. Defaults to None.
        """
        BuiltinHandler.serializer = serializer

    @staticmethod
    def dumps(obj: Any) -> str:  # noqa: ANN401
        return json.dumps(obj, cls=BuiltinHandler.serializer)

    @staticmethod
    def dump_bytes(obj: Any) -> bytes:  # noqa: ANN401
        return json.dumps(obj, cls=BuiltinHandler.serializer).encode("utf-8")

    @staticmethod
    def loads(json_string: str | bytes | bytearray) -> Any:  # noqa: ANN401
        return json.loads(json_string)

serializer class-attribute instance-attribute

serializer: type[JSONEncoder] | None = None

__init__

__init__(
    serializer: type[JSONEncoder] | None = None,
) -> None

Uses the json module from the Python standard library.

Parameters:

  • serializer (type[JSONEncoder] | None, default: None ) –

    A custom JSONEncode to handle serializing fields that the build in json.dumps cannot handle, for example UUID and datetime. Defaults to None.

Source code in meilisearch_python_sdk/json_handler.py
def __init__(self, serializer: type[json.JSONEncoder] | None = None) -> None:
    """Uses the json module from the Python standard library.

    Args:
        serializer: A custom JSONEncode to handle serializing fields that the build in
            json.dumps cannot handle, for example UUID and datetime. Defaults to None.
    """
    BuiltinHandler.serializer = serializer

dumps staticmethod

dumps(obj: Any) -> str
Source code in meilisearch_python_sdk/json_handler.py
@staticmethod
def dumps(obj: Any) -> str:  # noqa: ANN401
    return json.dumps(obj, cls=BuiltinHandler.serializer)

dump_bytes staticmethod

dump_bytes(obj: Any) -> bytes
Source code in meilisearch_python_sdk/json_handler.py
@staticmethod
def dump_bytes(obj: Any) -> bytes:  # noqa: ANN401
    return json.dumps(obj, cls=BuiltinHandler.serializer).encode("utf-8")

loads staticmethod

loads(json_string: str | bytes | bytearray) -> Any
Source code in meilisearch_python_sdk/json_handler.py
@staticmethod
def loads(json_string: str | bytes | bytearray) -> Any:  # noqa: ANN401
    return json.loads(json_string)

OrjsonHandler

Bases: _JsonHandler

Source code in meilisearch_python_sdk/json_handler.py
class OrjsonHandler(_JsonHandler):
    def __init__(self) -> None:
        if orjson is None:  # pragma: no cover
            raise ValueError("orjson must be installed to use the OrjsonHandler")

    @staticmethod
    def dumps(obj: Any) -> str:  # noqa: ANN401
        return orjson.dumps(obj).decode("utf-8")  # pyrefly: ignore[missing-attribute]

    @staticmethod
    def dump_bytes(obj: Any) -> bytes:  # noqa: ANN401
        return orjson.dumps(obj)  # pyrefly: ignore[missing-attribute]

    @staticmethod
    def loads(json_string: str | bytes | bytearray) -> Any:  # noqa: ANN401
        return orjson.loads(json_string)  # pyrefly: ignore[missing-attribute]

__init__

__init__() -> None
Source code in meilisearch_python_sdk/json_handler.py
def __init__(self) -> None:
    if orjson is None:  # pragma: no cover
        raise ValueError("orjson must be installed to use the OrjsonHandler")

dumps staticmethod

dumps(obj: Any) -> str
Source code in meilisearch_python_sdk/json_handler.py
@staticmethod
def dumps(obj: Any) -> str:  # noqa: ANN401
    return orjson.dumps(obj).decode("utf-8")  # pyrefly: ignore[missing-attribute]

dump_bytes staticmethod

dump_bytes(obj: Any) -> bytes
Source code in meilisearch_python_sdk/json_handler.py
@staticmethod
def dump_bytes(obj: Any) -> bytes:  # noqa: ANN401
    return orjson.dumps(obj)  # pyrefly: ignore[missing-attribute]

loads staticmethod

loads(json_string: str | bytes | bytearray) -> Any
Source code in meilisearch_python_sdk/json_handler.py
@staticmethod
def loads(json_string: str | bytes | bytearray) -> Any:  # noqa: ANN401
    return orjson.loads(json_string)  # pyrefly: ignore[missing-attribute]