### Install orjson with pip Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md To install orjson, specify the package in your requirements.in or requirements.txt file. Ensure you use a version compatible with your Python environment. ```text orjson >= 3.10,<4 ``` -------------------------------- ### Install orjson with pyproject.toml Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md To install orjson, specify the package in your pyproject.toml file. This format is commonly used with modern Python packaging tools. ```toml orjson = "^3.10" ``` -------------------------------- ### Build orjson with Maturin Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Use this command to build orjson from source. Ensure Rust 1.89+, a C compiler, and maturin are installed. ```sh maturin build --release --strip ``` -------------------------------- ### Serializing UTC Datetime with OPT_UTC_Z Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Shows how to format UTC timezone information as 'Z' instead of '+00:00' using the OPT_UTC_Z option. ```python >>> import orjson, datetime, zoneinfo >>> orjson.dumps( datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")), ) b'"1970-01-01T00:00:00+00:00"' >>> orjson.dumps( datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")), option=orjson.OPT_UTC_Z ) b'"1970-01-01T00:00:00Z"' ``` -------------------------------- ### Serialize and Deserialize with Options Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Demonstrates serializing a Python dictionary containing various data types (datetime, numpy array) with specific options and then deserializing the resulting bytes. Use `orjson.OPT_NAIVE_UTC` for naive datetime serialization and `orjson.OPT_SERIALIZE_NUMPY` for numpy arrays. ```python >>> import orjson, datetime, numpy >>> data = { "type": "job", "created_at": datetime.datetime(1970, 1, 1), "status": "โŒ", "payload": numpy.array([[1, 2], [3, 4]]), } >>> orjson.dumps(data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY) b'{"type":"job","created_at":"1970-01-01T00:00:00+00:00","status":" f0 9f 86 97","payload":[[1,2],[3,4]]}' >>> orjson.loads(_) {'type': 'job', 'created_at': '1970-01-01T00:00:00+00:00', 'status': '๐Ÿ†—', 'payload': [[1, 2], [3, 4]]} ``` -------------------------------- ### Passthrough Subclasses with Custom Default Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Demonstrates how to use OPT_PASSTHROUGH_SUBCLASS with a custom default function to serialize subclasses of built-in types. ```python >>> import orjson >>> class Secret(str): pass def default(obj): if isinstance(obj, Secret): return "******" raise TypeError >>> orjson.dumps(Secret("zxc")) b'"zxc"' >>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS) TypeError: Type is not JSON serializable: Secret >>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=default) b'"******"' ``` -------------------------------- ### Sorting Dictionary Keys with OPT_SORT_KEYS Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Illustrates the use of OPT_SORT_KEYS to serialize dictionary keys in a deterministic, sorted order. This option has a performance penalty. ```python >>> import orjson >>> orjson.dumps({"b": 1, "c": 2, "a": 3}) b'{"b":1,"c":2,"a":3}' >>> orjson.dumps({"b": 1, "c": 2, "a": 3}, option=orjson.OPT_SORT_KEYS) b'{"a":3,"b":1,"c":2}' ``` ```python >>> import orjson >>> orjson.dumps({"a": 1, "รค": 2, "A": 3}, option=orjson.OPT_SORT_KEYS) b'{"A":3,"a":1,"\xc3\xa4":2}' ``` -------------------------------- ### Pretty-print JSON with OPT_INDENT_2 Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Employ the OPT_INDENT_2 option for pretty-printing JSON output with a two-space indent, similar to `indent=2` in the standard library. This option is compatible with other options but results in larger output and slower serialization. ```python import orjson orjson.dumps({"a": "b", "c": {"d": True}, "e": [1, 2]}) ``` ```python import orjson orjson.dumps( {"a": "b", "c": {"d": True}, "e": [1, 2]}, option=orjson.OPT_INDENT_2 ) ``` -------------------------------- ### Serialize Large Integers with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Demonstrates orjson's default serialization of 64-bit integers and the behavior when `OPT_STRICT_INTEGER` is used, which raises an error for values exceeding the 53-bit range. ```python >>> import orjson >>> orjson.dumps(9007199254740992) b'9007199254740992' >>> orjson.dumps(9007199254740992, option=orjson.OPT_STRICT_INTEGER) JSONEncodeError: Integer exceeds 53-bit range >>> orjson.dumps(-9007199254740992, option=orjson.OPT_STRICT_INTEGER) JSONEncodeError: Integer exceeds 53-bit range ``` -------------------------------- ### Including Pre-serialized JSON with orjson.Fragment Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Demonstrates using orjson.Fragment to embed already serialized JSON within a larger JSON document without re-parsing. ```python >>> import orjson >>> orjson.dumps({"key": "zxc", "data": orjson.Fragment(b'{"a": "b", "c": 1}')}) b'{"key":"zxc","data":{"a": "b", "c": 1}}' ``` -------------------------------- ### Combining orjson Options for Serialization Source: https://context7.com/anthropics/orjson/llms.txt Shows how to combine multiple orjson options using the bitwise OR operator for advanced serialization features. Options include naive UTC, numpy serialization, indentation, key sorting, and newline appending. ```python import orjson, datetime, numpy # Serialize a complex record with multiple option flags data = { "type": "job", "created_at": datetime.datetime(1970, 1, 1), "status": "๐Ÿ†—", "payload": numpy.array([[1, 2], [3, 4]]), } result = orjson.dumps( data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY, ) assert result == ( b'{"type":"job","created_at":"1970-01-01T00:00:00+00:00",' b'"status":"\xf0\x9f\x86\x97","payload":[[1,2],[3,4]]}' ) # Round-trip parsed = orjson.loads(result) # โ†’ {'type': 'job', 'created_at': '1970-01-01T00:00:00+00:00', 'status': '๐Ÿ†—', 'payload': [[1,2],[3,4]]} # Pretty-print + sort + UTC-Z + newline import zoneinfo event = {"z": 26, "a": 1, "ts": datetime.datetime(2024, 6, 1, 12, 0, tzinfo=zoneinfo.ZoneInfo("UTC"))} pretty = orjson.dumps( event, option=orjson.OPT_INDENT_2 | orjson.OPT_SORT_KEYS | orjson.OPT_UTC_Z | orjson.OPT_APPEND_NEWLINE, ) print(pretty.decode()) # { # "a": 1, # "ts": "2024-06-01T12:00:00Z", # "z": 26 # } ``` -------------------------------- ### Allow non-string dictionary keys with OPT_NON_STR_KEYS Source: https://context7.com/anthropics/orjson/llms.txt Enable serialization of dictionary keys that are not strings, including `int`, `float`, `bool`, `None`, `datetime.datetime`, `datetime.date`, `datetime.time`, `enum.Enum`, and `uuid.UUID`. This option is compatible with `OPT_SORT_KEYS` and offers faster performance compared to other libraries. ```python import orjson, datetime, uuid # int keys assert orjson.dumps({1: "a", 2: "b"}, option=orjson.OPT_NON_STR_KEYS) == b'{"1":"a","2":"b"}' ``` ```python # UUID keys assert orjson.dumps( {uuid.UUID("7202d115-7ff3-4c81-a7c1-2a1f067b1ece"): [1, 2, 3]}, option=orjson.OPT_NON_STR_KEYS, ) == b'{"7202d115-7ff3-4c81-a7c1-2a1f067b1ece":[1,2,3]}' ``` ```python # datetime keys with combined options assert orjson.dumps( {datetime.datetime(1970, 1, 1): "epoch"}, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_NAIVE_UTC, ) == b'{"1970-01-01T00:00:00+00:00":"epoch"}' ``` -------------------------------- ### Serialize Special Float Values with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Illustrates how orjson serializes NaN, Infinity, and -Infinity as `null`, contrasting with Python's standard `json` module. ```python >>> import orjson, json >>> orjson.dumps([float("NaN"), float("Infinity"), float("-Infinity")]) b'[null,null,null]' >>> json.dumps([float("NaN"), float("Infinity"), float("-Infinity")]) '[NaN, Infinity, -Infinity]' ``` -------------------------------- ### Pretty-print JSON with 2-space indentation using orjson Source: https://context7.com/anthropics/orjson/llms.txt Use OPT_INDENT_2 for human-readable, indented JSON output. This option is compatible with all other options and offers significant speed improvements over the standard library's json module. ```python import orjson data = {"a": "b", "c": {"d": True}, "e": [1, 2]} compact = orjson.dumps(data) assert compact == b'{"a":"b","c":{"d":true},"e":[1,2]}' pretty = orjson.dumps(data, option=orjson.OPT_INDENT_2) assert pretty == b'{\n "a": "b",\n "c": {\n "d": true\n },\n "e": [\n 1,\n 2\n ]\n}' print(pretty.decode()) ``` -------------------------------- ### Serialize Naive Datetimes as UTC with OPT_NAIVE_UTC Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Utilize the OPT_NAIVE_UTC option to serialize `datetime.datetime` objects without timezone information as UTC. This option does not affect `datetime.datetime` objects that already have `tzinfo` set. ```python import orjson, datetime orjson.dumps( datetime.datetime(1970, 1, 1, 0, 0, 0), ) ``` ```python import orjson, datetime orjson.dumps( datetime.datetime(1970, 1, 1, 0, 0, 0), option=orjson.OPT_NAIVE_UTC, ) ``` -------------------------------- ### Serialize DatetimeEnum with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Demonstrates native serialization of enums containing datetime objects. The OPT_NAIVE_UTC option formats the output with timezone information. ```python >>> import enum, datetime, orjson >>> class DatetimeEnum(enum.Enum): EPOCH = datetime.datetime(1970, 1, 1, 0, 0, 0) >>> orjson.dumps(DatetimeEnum.EPOCH) b'"1970-01-01T00:00:00"' >>> orjson.dumps(DatetimeEnum.EPOCH, option=orjson.OPT_NAIVE_UTC) b'"1970-01-01T00:00:00+00:00"' ``` -------------------------------- ### OPT_NAIVE_UTC Source: https://context7.com/anthropics/orjson/llms.txt Treat naive datetimes as UTC. Serializes `datetime.datetime` objects that have no `tzinfo` as if they were UTC, appending `+00:00`. Has no effect on timezone-aware datetimes. ```APIDOC ## OPT_NAIVE_UTC ### Description Treat naive datetimes as UTC. Serializes `datetime.datetime` objects that have no `tzinfo` as if they were UTC, appending `+00:00`. Has no effect on timezone-aware datetimes. ### Usage Examples ```python import orjson, datetime naive = datetime.datetime(1970, 1, 1, 0, 0, 0) assert orjson.dumps(naive) == b'"1970-01-01T00:00:00"' assert orjson.dumps(naive, option=orjson.OPT_NAIVE_UTC) == b'"1970-01-01T00:00:00+00:00"' # Combine with OPT_NON_STR_KEYS to use naive datetimes as dict keys data = {datetime.datetime(2024, 1, 1): "start", datetime.datetime(2024, 12, 31): "end"} result = orjson.dumps(data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_NON_STR_KEYS) assert result == b'{"2024-01-01T00:00:00+00:00":"start","2024-12-31T00:00:00+00:00":"end"}' ``` ``` -------------------------------- ### Serialize Dataclasses Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md orjson natively serializes instances of `dataclasses.dataclass` efficiently, outperforming other libraries significantly. ```APIDOC ## Dataclass Serialization ### Description orjson serializes instances of `dataclasses.dataclass` natively and efficiently. ### Example ```python import dataclasses, orjson, typing @dataclasses.dataclass class Member: id: int active: bool = dataclasses.field(default=False) @dataclasses.dataclass class Object: id: int name: str members: typing.List[Member] # Example usage: # orjson.dumps(Object(1, "a", [Member(1, True), Member(2)])) # Expected output: b'{"id":1,"name":"a","members":[{"id":1,"active":true},{"id":2,"active":false}]}' ``` ### Notes - Supports all dataclass variants, including those with `__slots__`, frozen dataclasses, optional/default attributes, and subclasses. - There is a performance benefit to not using `__slots__`. - Dataclasses are serialized as maps in the order of attribute definition. ``` -------------------------------- ### Sort dictionary keys with OPT_SORT_KEYS Source: https://context7.com/anthropics/orjson/llms.txt The `OPT_SORT_KEYS` option serializes dictionary keys in ascending lexicographical order, similar to `sort_keys=True` in the standard `json` library. This is useful for generating deterministic output for hashing or snapshot testing. orjson remains significantly faster than the standard library even with this option. ```python import orjson data = {"b": 1, "c": 2, "a": 3} assert orjson.dumps(data) == b'{"b":1,"c":2,"a":3}' # insertion order assert orjson.dumps(data, option=orjson.OPT_SORT_KEYS) == b'{"a":3,"b":1,"c":2}' ``` ```python # Sorting is byte-order, not locale-aware (same as stdlib) assert orjson.dumps({"a": 1, "รค": 2, "A": 3}, option=orjson.OPT_SORT_KEYS) == \ b'{"A":3,"a":1,"\xc3\xa4":2}' ``` -------------------------------- ### Route datetimes through default with OPT_PASSTHROUGH_DATETIME Source: https://context7.com/anthropics/orjson/llms.txt Employ OPT_PASSTHROUGH_DATETIME to bypass automatic datetime serialization and direct instances to the default callable for custom formatting. This enables formats like HTTP dates or Unix timestamps. ```python import orjson, datetime def default(obj): if isinstance(obj, datetime.datetime): return obj.strftime("%a, %d %b %Y %H:%M:%S GMT") if isinstance(obj, datetime.date): return obj.isoformat() raise TypeError # Default: RFC 3339 assert orjson.dumps({"ts": datetime.datetime(1970, 1, 1)}) == b'{"ts":"1970-01-01T00:00:00"}' # With passthrough: custom HTTP date format assert orjson.dumps( {"ts": datetime.datetime(1970, 1, 1)}, option=orjson.OPT_PASSTHROUGH_DATETIME, default=default, ) == b'{"ts":"Thu, 01 Jan 1970 00:00:00 GMT"}' ``` -------------------------------- ### Serialize CustomEnum with orjson and default Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Shows how to serialize enums with unsupported member types using a custom `default` function. The function must handle the specific custom object type. ```python >>> import enum, orjson >>> class Custom: def __init__(self, val): self.val = val def default(obj): if isinstance(obj, Custom): return obj.val raise TypeError class CustomEnum(enum.Enum): ONE = Custom(1) >>> orjson.dumps(CustomEnum.ONE, default=default) b'1' ``` -------------------------------- ### Sort Mixed-Type Keys with orjson Source: https://context7.com/anthropics/orjson/llms.txt Use OPT_NON_STR_KEYS and OPT_SORT_KEYS to serialize dictionaries with non-string keys, ensuring consistent output order. ```python import orjson import datetime result = orjson.dumps( {"other": 1, datetime.date(1970, 1, 5): 2, datetime.date(1970, 1, 3): 3}, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS, ) assert result == b'{"1970-01-03":3,"1970-01-05":2,"other":1}' ``` -------------------------------- ### Deserialize JSON to Python Objects Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md `loads()` deserializes JSON to Python objects. It accepts bytes, bytearray, memoryview, and str input. For optimal performance, use bytes, bytearray, or memoryview directly. ```APIDOC ## loads ### Description Deserializes JSON to Python objects. Accepts bytes, bytearray, memoryview, and str. ### Method Signature ```python def loads(__obj: Union[bytes, bytearray, memoryview, str]) -> Any: ... ``` ### Parameters - `__obj` (Union[bytes, bytearray, memoryview, str]): The JSON data to deserialize. ### Returns - `Any`: The deserialized Python object. ### Raises - `JSONDecodeError`: If the input is not valid UTF-8, contains invalid JSON (including NaN, Infinity, -Infinity), recurses too deeply (1024 levels), or if a buffer cannot be allocated. ### Notes - The input must be valid UTF-8. - orjson maintains a cache of map keys for performance, with keys at most 64 bytes and up to 2048 entries. - The global interpreter lock (GIL) is held during the call. - `JSONDecodeError` is a subclass of `json.JSONDecodeError` and `ValueError` for compatibility. ``` -------------------------------- ### Treat naive datetimes as UTC with OPT_NAIVE_UTC Source: https://context7.com/anthropics/orjson/llms.txt The `OPT_NAIVE_UTC` option serializes `datetime.datetime` objects without timezone information as if they were UTC, appending `+00:00`. This option does not affect timezone-aware datetimes. It can be combined with `OPT_NON_STR_KEYS` to use naive datetimes as dictionary keys. ```python import orjson, datetime naive = datetime.datetime(1970, 1, 1, 0, 0, 0) assert orjson.dumps(naive) == b'"1970-01-01T00:00:00"' assert orjson.dumps(naive, option=orjson.OPT_NAIVE_UTC) == b'"1970-01-01T00:00:00+00:00"' ``` ```python # Combine with OPT_NON_STR_KEYS to use naive datetimes as dict keys data = {datetime.datetime(2024, 1, 1): "start", datetime.datetime(2024, 12, 31): "end"} result = orjson.dumps(data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_NON_STR_KEYS) assert result == b'{"2024-01-01T00:00:00+00:00":"start","2024-12-31T00:00:00+00:00":"end"}' ``` -------------------------------- ### Serialize Dataclasses with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md orjson natively serializes `dataclasses.dataclass` instances efficiently. Attributes are serialized in the order they are defined in the class. ```python >>> import dataclasses, orjson, typing @dataclasses.dataclass class Member: id: int active: bool = dataclasses.field(default=False) @dataclasses.dataclass class Object: id: int name: str members: typing.List[Member] >>> orjson.dumps(Object(1, "a", [Member(1, True), Member(2)])) b'{"id":1,"name":"a","members":[{"id":1,"active":true},{"id":2,"active":false}]}' ``` -------------------------------- ### OPT_NON_STR_KEYS Source: https://context7.com/anthropics/orjson/llms.txt Allow non-string dict keys. Enables serialization of `dict` keys of types other than `str`: `int`, `float`, `bool`, `None`, `datetime.datetime`, `datetime.date`, `datetime.time`, `enum.Enum`, and `uuid.UUID`. orjson benchmarks faster at this than other libraries. Compatible with `OPT_SORT_KEYS`. ```APIDOC ## OPT_NON_STR_KEYS ### Description Allow non-string dict keys. Enables serialization of `dict` keys of types other than `str`: `int`, `float`, `bool`, `None`, `datetime.datetime`, `datetime.date`, `datetime.time`, `enum.Enum`, and `uuid.UUID`. orjson benchmarks faster at this than other libraries. Compatible with `OPT_SORT_KEYS`. ### Usage Examples ```python import orjson, datetime, uuid # int keys assert orjson.dumps({1: "a", 2: "b"}, option=orjson.OPT_NON_STR_KEYS) == b'{"1":"a","2":"b"}' # UUID keys assert orjson.dumps( {uuid.UUID("7202d115-7ff3-4c81-a7c1-2a1f067b1ece"): [1, 2, 3]}, option=orjson.OPT_NON_STR_KEYS, ) == b'{"7202d115-7ff3-4c81-a7c1-2a1f067b1ece":[1,2,3]}' # datetime keys with combined options assert orjson.dumps( {datetime.datetime(1970, 1, 1): "epoch"}, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_NAIVE_UTC, ) == b'{"1970-01-01T00:00:00+00:00":"epoch"}' ``` ``` -------------------------------- ### orjson.loads Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Deserializes JSON bytes into Python objects. ```APIDOC ## orjson.loads ### Description Deserializes JSON bytes into Python objects. There was no change in deserialization behavior between version 2 and 3. ### Method `loads(__bytes: bytes) -> Any` ### Parameters - **__bytes** (bytes) - The JSON bytes to deserialize. ### Returns - **Any** - The deserialized Python object. ``` -------------------------------- ### OPT_SORT_KEYS Source: https://context7.com/anthropics/orjson/llms.txt Serialize dict keys in sorted order. Serializes `dict` keys in ascending lexicographic order, equivalent to `sort_keys=True` in the standard library. Useful for deterministic output (hashing, snapshot tests). Note: orjson is still ~6ร— faster than `json` even with this option enabled. ```APIDOC ## OPT_SORT_KEYS ### Description Serialize dict keys in sorted order. Serializes `dict` keys in ascending lexicographic order, equivalent to `sort_keys=True` in the standard library. Useful for deterministic output (hashing, snapshot tests). Note: orjson is still ~6ร— faster than `json` even with this option enabled. ### Usage Examples ```python import orjson data = {"b": 1, "c": 2, "a": 3} assert orjson.dumps(data) == b'{"b":1,"c":2,"a":3}' # insertion order assert orjson.dumps(data, option=orjson.OPT_SORT_KEYS) == b'{"a":3,"b":1,"c":2}' # Sorting is byte-order, not locale-aware (same as stdlib) assert orjson.dumps({"a": 1, "รค": 2, "A": 3}, option=orjson.OPT_SORT_KEYS) == \ b'{"A":3,"a":1,"\xc3\xa4":2}' ``` ``` -------------------------------- ### Use 'Z' suffix for UTC with OPT_UTC_Z Source: https://context7.com/anthropics/orjson/llms.txt The `OPT_UTC_Z` option serializes the UTC timezone using a 'Z' suffix instead of '+00:00', resulting in shorter, RFC 3339 compliant timestamps. ```python import orjson, datetime, zoneinfo dt = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")) assert orjson.dumps(dt) == b'"1970-01-01T00:00:00+00:00"' assert orjson.dumps(dt, option=orjson.OPT_UTC_Z) == b'"1970-01-01T00:00:00Z"' ``` -------------------------------- ### Serialize NumPy arrays and scalars with orjson Source: https://context7.com/anthropics/orjson/llms.txt Enable native serialization of NumPy types using OPT_SERIALIZE_NUMPY for significant performance gains. Requires contiguous C-order arrays and native endianness. Fallbacks to a provided default function for non-contiguous arrays. ```python import orjson, numpy # 2D integer array arr = numpy.array([[1, 2, 3], [4, 5, 6]]) assert orjson.dumps(arr, option=orjson.OPT_SERIALIZE_NUMPY) == b'[[1,2,3],[4,5,6]]' # Float array farr = numpy.array([1.1, 2.2, 3.3], dtype=numpy.float32) result = orjson.dumps(farr, option=orjson.OPT_SERIALIZE_NUMPY) # โ†’ b'[1.1,2.2,3.3]' # Bool array barr = numpy.array([True, False, True]) assert orjson.dumps(barr, option=orjson.OPT_SERIALIZE_NUMPY) == b'[true,false,true]' # numpy.datetime64 โ†’ RFC 3339 string (affected by datetime options) dt64 = numpy.datetime64("2021-01-01T00:00:00.172") assert orjson.dumps(dt64, option=orjson.OPT_SERIALIZE_NUMPY) == b'"2021-01-01T00:00:00.172000"' assert orjson.dumps( dt64, option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC | orjson.OPT_OMIT_MICROSECONDS, ) == b'"2021-01-01T00:00:00+00:00"' # Individual scalars assert orjson.dumps(numpy.float64(1.5), option=orjson.OPT_SERIALIZE_NUMPY) == b'1.5' assert orjson.dumps(numpy.int32(42), option=orjson.OPT_SERIALIZE_NUMPY) == b'42' # Non-contiguous arrays: fall through to default def default(obj): if isinstance(obj, numpy.ndarray): return obj.tolist() raise TypeError non_contiguous = numpy.asfortranarray(numpy.array([[1, 2], [3, 4]])) result = orjson.dumps(non_contiguous, option=orjson.OPT_SERIALIZE_NUMPY, default=default) ``` -------------------------------- ### Passthrough Dataclasses with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Use OPT_PASSTHROUGH_DATACLASS to allow dataclasses to be passed to the default serializer. This enables custom serialization logic for dataclasses but is significantly slower than default serialization. ```python import orjson, dataclasses @dataclasses.dataclass class User: id: str name: str password: str def default(obj): if isinstance(obj, User): return {"id": obj.id, "name": obj.name} raise TypeError orjson.dumps(User("3b1", "asd", "zxc")) ``` ```python import orjson, dataclasses @dataclasses.dataclass class User: id: str name: str password: str def default(obj): if isinstance(obj, User): return {"id": obj.id, "name": obj.name} raise TypeError orjson.dumps(User("3b1", "asd", "zxc"), option=orjson.OPT_PASSTHROUGH_DATACLASS) ``` ```python import orjson, dataclasses @dataclasses.dataclass class User: id: str name: str password: str def default(obj): if isinstance(obj, User): return {"id": obj.id, "name": obj.name} raise TypeError orjson.dumps( User("3b1", "asd", "zxc"), option=orjson.OPT_PASSTHROUGH_DATACLASS, default=default, ) ``` -------------------------------- ### Handle Custom Types with default Callable Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Specify a 'default' callable to serialize unsupported types like decimal.Decimal. Raise TypeError if a type cannot be handled to avoid implicit None serialization. The callable can be nested up to 254 times. ```python import orjson, decimal def default(obj): if isinstance(obj, decimal.Decimal): return str(obj) raise TypeError orjson.dumps(decimal.Decimal("0.0842389659712649442845"), default=default) ``` ```python import orjson, decimal def default(obj): if isinstance(obj, decimal.Decimal): return str(obj) raise TypeError orjson.dumps({1, 2}, default=default) ``` ```python import orjson, json def default(obj): if isinstance(obj, decimal.Decimal): return str(obj) orjson.dumps({"set":{1, 2}}, default=default) ``` ```python import orjson, json def default(obj): if isinstance(obj, decimal.Decimal): return str(obj) json.dumps({"set":{1, 2}}, default=default) ``` -------------------------------- ### Serialize Non-String Dictionary Keys with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Use OPT_NON_STR_KEYS to serialize dictionary keys of types other than strings, such as UUIDs and datetimes. This option can be slower for string keys and carries a risk of creating duplicate keys if non-string keys serialize to the same string representation. ```python import orjson, datetime, uuid orjson.dumps( {uuid.UUID("7202d115-7ff3-4c81-a7c1-2a1f067b1ece"): [1, 2, 3]}, option=orjson.OPT_NON_STR_KEYS, ) ``` ```python import orjson, datetime, uuid orjson.dumps( {datetime.datetime(1970, 1, 1, 0, 0, 0): [1, 2, 3]}, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_NAIVE_UTC, ) ``` ```python import orjson, datetime orjson.dumps( {"other": 1, datetime.date(1970, 1, 5): 2, datetime.date(1970, 1, 3): 3}, option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS ) ``` -------------------------------- ### OPT_UTC_Z Source: https://context7.com/anthropics/orjson/llms.txt Use "Z" suffix for UTC timestamps. Serializes the UTC timezone as `Z` instead of `+00:00`, producing shorter RFC 3339 timestamps. ```APIDOC ## OPT_UTC_Z ### Description Use "Z" suffix for UTC timestamps. Serializes the UTC timezone as `Z` instead of `+00:00`, producing shorter RFC 3339 timestamps. ### Usage Examples ```python import orjson, datetime, zoneinfo dt = datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")) assert orjson.dumps(dt) == b'"1970-01-01T00:00:00+00:00"' assert orjson.dumps(dt, option=orjson.OPT_UTC_Z) == b'"1970-01-01T00:00:00Z"' ``` ``` -------------------------------- ### Route dataclasses through default with OPT_PASSTHROUGH_DATACLASS Source: https://context7.com/anthropics/orjson/llms.txt Use OPT_PASSTHROUGH_DATACLASS to prevent automatic dataclass serialization and pass instances to the default callable for custom field handling. This is useful for excluding sensitive fields like passwords. ```python import orjson, dataclasses @dataclasses.dataclass class User: id: str name: str password: str def default(obj): if isinstance(obj, User): return {"id": obj.id, "name": obj.name} # exclude password raise TypeError # Default: all fields serialized assert orjson.dumps(User("3b1", "alice", "secret")) == b'{"id":"3b1","name":"alice","password":"secret"}' # With passthrough: only fields returned by default assert orjson.dumps( User("3b1", "alice", "secret"), option=orjson.OPT_PASSTHROUGH_DATACLASS, default=default, ) == b'{"id":"3b1","name":"alice"}' ``` -------------------------------- ### Passthrough Datetimes with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Use OPT_PASSTHROUGH_DATETIME to pass datetime.datetime, datetime.date, and datetime.time instances to the default serializer. This allows for custom formatting of datetime objects, such as HTTP dates, but requires a custom default function. ```python import orjson, datetime def default(obj): if isinstance(obj, datetime.datetime): return obj.strftime("%a, %d %b %Y %H:%M:%S GMT") raise TypeError orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)}) ``` ```python import orjson, datetime def default(obj): if isinstance(obj, datetime.datetime): return obj.strftime("%a, %d %b %Y %H:%M:%S GMT") raise TypeError orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)}, option=orjson.OPT_PASSTHROUGH_DATETIME) ``` ```python import orjson, datetime def default(obj): if isinstance(obj, datetime.datetime): return obj.strftime("%a, %d %b %Y %H:%M:%S GMT") raise TypeError orjson.dumps( {"created_at": datetime.datetime(1970, 1, 1)}, option=orjson.OPT_PASSTHROUGH_DATETIME, default=default, ) ``` -------------------------------- ### Append Newline with OPT_APPEND_NEWLINE Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Use the OPT_APPEND_NEWLINE option to append a newline character '\n' to the serialized output. This is an optimization for the common pattern of `dumps(...) + "\n"`. ```python import orjson orjson.dumps([], option=orjson.OPT_APPEND_NEWLINE) ``` -------------------------------- ### UTF-8 Strictness and Error Handling in orjson Source: https://context7.com/anthropics/orjson/llms.txt Illustrates orjson's strict UTF-8 enforcement, rejecting surrogates that the standard json library accepts. For invalid UTF-8 bytes, decode first using errors='replace' or errors='surrogateescape'. ```python import orjson, json # Surrogates rejected by orjson, accepted by json try: orjson.dumps('\ud800') except orjson.JSONEncodeError as e: print(e) # str is not valid UTF-8: surrogates not allowed json.dumps('\ud800') # โ†’ '"\ud800"' (accepted but non-compliant) try: orjson.loads('"\ud800"') except orjson.JSONDecodeError as e: print(e) # unexpected end of hex escape ... # Best-effort deserialization of bad bytes try: orjson.loads(b'"\xed\xa0\x80"') # invalid UTF-8 except orjson.JSONDecodeError: pass result = orjson.loads(b'"\xed\xa0\x80"'.decode("utf-8", "replace")) # โ†’ '' (replacement characters) # float special values: NaN/Infinity โ†’ null (not valid JSON literals) assert orjson.dumps([float("NaN"), float("Infinity"), float("-Infinity")]) == b'[null,null,null]' # json produces non-compliant output: # json.dumps([float("NaN"), float("Infinity")]) โ†’ '[NaN, Infinity]' ``` -------------------------------- ### Serialize numpy.datetime64 with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md Numpy datetime64 instances are serialized as RFC 3339 strings. Datetime options can affect the output format. Using `OPT_NAIVE_UTC` and `OPT_OMIT_MICROSECONDS` can alter the timezone and precision. ```python >>> import orjson, numpy >>> orjson.dumps( numpy.datetime64("2021-01-01T00:00:00.172"), option=orjson.OPT_SERIALIZE_NUMPY, ) b'"2021-01-01T00:00:00.172000"' >>> orjson.dumps( numpy.datetime64("2021-01-01T00:00:00.172"), option=( orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC | orjson.OPT_OMIT_MICROSECONDS ), ) b'"2021-01-01T00:00:00+00:00"' ``` -------------------------------- ### Serialize Datetime Objects Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md orjson serializes `datetime.datetime` objects to RFC 3339 format and `datetime.time` and `datetime.date` objects to their string representations. ```APIDOC ## Datetime Serialization ### Description orjson serializes `datetime.datetime`, `datetime.time`, and `datetime.date` objects. ### `datetime.datetime` Serialization - Serialized to [RFC 3339](https://tools.ietf.org/html/rfc3339) format (e.g., `"1970-01-01T00:00:00+00:00"`). - Supports `tzinfo` instances from `None`, `datetime.timezone.utc`, `zoneinfo`, `pendulum`, `pytz`, or `dateutil`/`arrow`. - Using `zoneinfo.ZoneInfo` is fastest for timezones. ### `datetime.time` Serialization - Serialized to string format (e.g., `"12:00:15.000290"`). - `tzinfo` must not be set. ### `datetime.date` Serialization - Serialized to string format (e.g., `"1900-01-02"`). ### Options - `orjson.OPT_PASSTHROUGH_DATETIME`: Disables serialization of `datetime` objects. - `orjson.OPT_UTC_Z`: Uses "Z" suffix for UTC time instead of `"+00:00"`. - `orjson.OPT_NAIVE_UTC`: Assumes naive datetimes are UTC. ### Errors - `JSONEncodeError` is raised for `tzinfo` errors. ### Examples ```python import orjson, datetime, zoneinfo # Example for datetime.datetime with timezone # orjson.dumps( # datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=zoneinfo.ZoneInfo("Australia/Adelaide")) # ) # Expected output: b'"2018-12-01T02:03:04.000009+10:30"' # Example for datetime.datetime without timezone # orjson.dumps(datetime.datetime(2100, 9, 1, 21, 55, 2)) # Expected output: b'"2100-09-01T21:55:02"' # Example for datetime.time # orjson.dumps(datetime.time(12, 0, 15, 290)) # Expected output: b'"12:00:15.000290"' # Example for datetime.date # orjson.dumps(datetime.date(1900, 1, 2)) # Expected output: b'"1900-01-02"' ``` ``` -------------------------------- ### Serialize uuid.UUID with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md orjson serializes `uuid.UUID` instances into RFC 4122 formatted strings. This is a standard and efficient way to represent UUIDs in JSON. ```python >>> import orjson, uuid >>> orjson.dumps(uuid.uuid5(uuid.NAMESPACE_DNS, "python.org")) b'"886313e1-3b8a-5372-9b90-0c9aee199e5d"' ``` -------------------------------- ### Route subclasses through default with OPT_PASSTHROUGH_SUBCLASS Source: https://context7.com/anthropics/orjson/llms.txt Utilize OPT_PASSTHROUGH_SUBCLASS to prevent automatic serialization of subclasses of built-in types, routing them to the default callable instead. This is beneficial for types with added semantic meaning, like masked secrets. ```python import orjson class Secret(str): pass class UserID(int): pass def default(obj): if isinstance(obj, Secret): return "***" if isinstance(obj, UserID): return {"id": int(obj)} raise TypeError # Default: subclasses serialized as their base type assert orjson.dumps(Secret("password123")) == b'"password123"' assert orjson.dumps(UserID(42)) == b'42' # With passthrough: routed through default assert orjson.dumps(Secret("password123"), option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=default) == b'"***"' assert orjson.dumps(UserID(42), option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=default) == b'{"id":42}' ``` -------------------------------- ### Serialize Datetime Objects with orjson Source: https://github.com/anthropics/orjson/blob/anthropic-3.11.7/README.md orjson serializes `datetime.datetime` objects to RFC 3339 format. It supports timezones from `zoneinfo`, `pendulum`, `pytz`, and `dateutil`/`arrow`. `datetime.time` objects must not have `tzinfo`, and `datetime.date` objects serialize directly. ```python >>> import orjson, datetime, zoneinfo >>> orjson.dumps( datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=zoneinfo.ZoneInfo("Australia/Adelaide")) ) b'"2018-12-01T02:03:04.000009+10:30"' >>> orjson.dumps( datetime.datetime(2100, 9, 1, 21, 55, 2).replace(tzinfo=zoneinfo.ZoneInfo("UTC")) ) b'"2100-09-01T21:55:02+00:00"' >>> orjson.dumps( datetime.datetime(2100, 9, 1, 21, 55, 2) ) b'"2100-09-01T21:55:02"' ``` ```python >>> import orjson, datetime >>> orjson.dumps(datetime.time(12, 0, 15, 290)) b'"12:00:15.000290"' ``` ```python >>> import orjson, datetime >>> orjson.dumps(datetime.date(1900, 1, 2)) b'"1900-01-02"' ``` -------------------------------- ### Reject NaN and Infinity floats with orjson Source: https://context7.com/anthropics/orjson/llms.txt Use OPT_DISALLOW_NAN to raise JSONEncodeError for NaN, Infinity, or -Infinity float values. The default behavior serializes these as null. ```python import orjson, math # Default behavior: NaN/Infinity โ†’ null assert orjson.dumps([float("nan"), float("inf"), float("-inf")]) == b'[null,null,null]' # With OPT_DISALLOW_NAN: raises instead try: orjson.dumps(float("nan"), option=orjson.OPT_DISALLOW_NAN) except orjson.JSONEncodeError as e: print(e) # NaN is not permitted try: orjson.dumps(math.inf, option=orjson.OPT_DISALLOW_NAN) except orjson.JSONEncodeError as e: print(e) # Infinity is not permitted ``` -------------------------------- ### Strip microseconds with OPT_OMIT_MICROSECONDS Source: https://context7.com/anthropics/orjson/llms.txt Use `OPT_OMIT_MICROSECONDS` to exclude the microsecond component from `datetime.datetime` and `datetime.time` objects during serialization, producing cleaner timestamps when sub-second precision is not required. ```python import orjson, datetime dt = datetime.datetime(1970, 1, 1, 0, 0, 0, 1) assert orjson.dumps(dt) == b'"1970-01-01T00:00:00.000001"' assert orjson.dumps(dt, option=orjson.OPT_OMIT_MICROSECONDS) == b'"1970-01-01T00:00:00"' ``` ```python t = datetime.time(12, 0, 15, 290) assert orjson.dumps(t) == b'"12:00:15.000290"' assert orjson.dumps(t, option=orjson.OPT_OMIT_MICROSECONDS) == b'"12:00:15"' ```