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
__init__
¶
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
dumps
staticmethod
¶
dump_bytes
staticmethod
¶
OrjsonHandler
¶
Bases: _JsonHandler