METADATA 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  1. Metadata-Version: 2.4
  2. Name: orjson
  3. Version: 3.11.5
  4. Classifier: Development Status :: 5 - Production/Stable
  5. Classifier: Intended Audience :: Developers
  6. Classifier: License :: OSI Approved :: Apache Software License
  7. Classifier: License :: OSI Approved :: MIT License
  8. Classifier: Operating System :: MacOS
  9. Classifier: Operating System :: Microsoft :: Windows
  10. Classifier: Operating System :: POSIX :: Linux
  11. Classifier: Programming Language :: Python :: 3
  12. Classifier: Programming Language :: Python :: 3.9
  13. Classifier: Programming Language :: Python :: 3.10
  14. Classifier: Programming Language :: Python :: 3.11
  15. Classifier: Programming Language :: Python :: 3.12
  16. Classifier: Programming Language :: Python :: 3.13
  17. Classifier: Programming Language :: Python :: 3.14
  18. Classifier: Programming Language :: Python :: 3.15
  19. Classifier: Programming Language :: Python :: Implementation :: CPython
  20. Classifier: Programming Language :: Python
  21. Classifier: Programming Language :: Rust
  22. Classifier: Typing :: Typed
  23. License-File: LICENSE-APACHE
  24. License-File: LICENSE-MIT
  25. Summary: Fast, correct Python JSON library supporting dataclasses, datetimes, and numpy
  26. License-Expression: Apache-2.0 OR MIT
  27. Requires-Python: >=3.9
  28. Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
  29. Project-URL: source, https://github.com/ijl/orjson
  30. Project-URL: documentation, https://github.com/ijl/orjson
  31. Project-URL: changelog, https://github.com/ijl/orjson/blob/master/CHANGELOG.md
  32. # orjson
  33. orjson is a fast, correct JSON library for Python. It
  34. [benchmarks](https://github.com/ijl/orjson?tab=readme-ov-file#performance) as the fastest Python
  35. library for JSON and is more correct than the standard json library or other
  36. third-party libraries. It serializes
  37. [dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass),
  38. [datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime),
  39. [numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy), and
  40. [UUID](https://github.com/ijl/orjson?tab=readme-ov-file#uuid) instances natively.
  41. [orjson.dumps()](https://github.com/ijl/orjson?tab=readme-ov-file#serialize) is
  42. something like 10x as fast as `json`, serializes
  43. common types and subtypes, has a `default` parameter for the caller to specify
  44. how to serialize arbitrary types, and has a number of flags controlling output.
  45. [orjson.loads()](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize)
  46. is something like 2x as fast as `json`, and is strictly compliant with UTF-8 and
  47. RFC 8259 ("The JavaScript Object Notation (JSON) Data Interchange Format").
  48. Reading from and writing to files, line-delimited JSON files, and so on is
  49. not provided by the library.
  50. orjson supports CPython 3.9, 3.10, 3.11, 3.12, 3.13, 3.14, and 3.15.
  51. It distributes amd64/x86_64/x64, i686/x86, aarch64/arm64/armv8, arm7,
  52. ppc64le/POWER8, and s390x wheels for Linux, amd64 and aarch64 wheels
  53. for macOS, and amd64, i686, and aarch64 wheels for Windows.
  54. Wheels published to PyPI for amd64 run on x86-64-v1 (2003)
  55. or later, but will at runtime use AVX-512 if available for a
  56. significant performance benefit; aarch64 wheels run on ARMv8-A (2011) or
  57. later.
  58. orjson does not and will not support PyPy, embedded Python builds for
  59. Android/iOS, or PEP 554 subinterpreters.
  60. orjson may support PEP 703 free-threading when it is stable.
  61. Releases follow semantic versioning and serializing a new object type
  62. without an opt-in flag is considered a breaking change.
  63. orjson is licensed under both the Apache 2.0 and MIT licenses. The
  64. repository and issue tracker is
  65. [github.com/ijl/orjson](https://github.com/ijl/orjson), and patches may be
  66. submitted there. There is a
  67. [CHANGELOG](https://github.com/ijl/orjson/blob/master/CHANGELOG.md)
  68. available in the repository.
  69. 1. [Usage](https://github.com/ijl/orjson?tab=readme-ov-file#usage)
  70. 1. [Install](https://github.com/ijl/orjson?tab=readme-ov-file#install)
  71. 2. [Quickstart](https://github.com/ijl/orjson?tab=readme-ov-file#quickstart)
  72. 3. [Migrating](https://github.com/ijl/orjson?tab=readme-ov-file#migrating)
  73. 4. [Serialize](https://github.com/ijl/orjson?tab=readme-ov-file#serialize)
  74. 1. [default](https://github.com/ijl/orjson?tab=readme-ov-file#default)
  75. 2. [option](https://github.com/ijl/orjson?tab=readme-ov-file#option)
  76. 3. [Fragment](https://github.com/ijl/orjson?tab=readme-ov-file#fragment)
  77. 5. [Deserialize](https://github.com/ijl/orjson?tab=readme-ov-file#deserialize)
  78. 2. [Types](https://github.com/ijl/orjson?tab=readme-ov-file#types)
  79. 1. [dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass)
  80. 2. [datetime](https://github.com/ijl/orjson?tab=readme-ov-file#datetime)
  81. 3. [enum](https://github.com/ijl/orjson?tab=readme-ov-file#enum)
  82. 4. [float](https://github.com/ijl/orjson?tab=readme-ov-file#float)
  83. 5. [int](https://github.com/ijl/orjson?tab=readme-ov-file#int)
  84. 6. [numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy)
  85. 7. [str](https://github.com/ijl/orjson?tab=readme-ov-file#str)
  86. 8. [uuid](https://github.com/ijl/orjson?tab=readme-ov-file#uuid)
  87. 3. [Testing](https://github.com/ijl/orjson?tab=readme-ov-file#testing)
  88. 4. [Performance](https://github.com/ijl/orjson?tab=readme-ov-file#performance)
  89. 1. [Latency](https://github.com/ijl/orjson?tab=readme-ov-file#latency)
  90. 2. [Reproducing](https://github.com/ijl/orjson?tab=readme-ov-file#reproducing)
  91. 5. [Questions](https://github.com/ijl/orjson?tab=readme-ov-file#questions)
  92. 6. [Packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging)
  93. 7. [License](https://github.com/ijl/orjson?tab=readme-ov-file#license)
  94. ## Usage
  95. ### Install
  96. To install a wheel from PyPI, install the `orjson` package.
  97. In `requirements.in` or `requirements.txt` format, specify:
  98. ```txt
  99. orjson >= 3.10,<4
  100. ```
  101. In `pyproject.toml` format, specify:
  102. ```toml
  103. orjson = "^3.10"
  104. ```
  105. To build a wheel, see [packaging](https://github.com/ijl/orjson?tab=readme-ov-file#packaging).
  106. ### Quickstart
  107. This is an example of serializing, with options specified, and deserializing:
  108. ```python
  109. >>> import orjson, datetime, numpy
  110. >>> data = {
  111. "type": "job",
  112. "created_at": datetime.datetime(1970, 1, 1),
  113. "status": "🆗",
  114. "payload": numpy.array([[1, 2], [3, 4]]),
  115. }
  116. >>> orjson.dumps(data, option=orjson.OPT_NAIVE_UTC | orjson.OPT_SERIALIZE_NUMPY)
  117. b'{"type":"job","created_at":"1970-01-01T00:00:00+00:00","status":"\xf0\x9f\x86\x97","payload":[[1,2],[3,4]]}'
  118. >>> orjson.loads(_)
  119. {'type': 'job', 'created_at': '1970-01-01T00:00:00+00:00', 'status': '🆗', 'payload': [[1, 2], [3, 4]]}
  120. ```
  121. ### Migrating
  122. orjson version 3 serializes more types than version 2. Subclasses of `str`,
  123. `int`, `dict`, and `list` are now serialized. This is faster and more similar
  124. to the standard library. It can be disabled with
  125. `orjson.OPT_PASSTHROUGH_SUBCLASS`.`dataclasses.dataclass` instances
  126. are now serialized by default and cannot be customized in a
  127. `default` function unless `option=orjson.OPT_PASSTHROUGH_DATACLASS` is
  128. specified. `uuid.UUID` instances are serialized by default.
  129. For any type that is now serialized,
  130. implementations in a `default` function and options enabling them can be
  131. removed but do not need to be. There was no change in deserialization.
  132. To migrate from the standard library, the largest difference is that
  133. `orjson.dumps` returns `bytes` and `json.dumps` returns a `str`.
  134. Users with `dict` objects using non-`str` keys should specify `option=orjson.OPT_NON_STR_KEYS`.
  135. `sort_keys` is replaced by `option=orjson.OPT_SORT_KEYS`.
  136. `indent` is replaced by `option=orjson.OPT_INDENT_2` and other levels of indentation are not
  137. supported.
  138. `ensure_ascii` is probably not relevant today and UTF-8 characters cannot be
  139. escaped to ASCII.
  140. ### Serialize
  141. ```python
  142. def dumps(
  143. __obj: Any,
  144. default: Optional[Callable[[Any], Any]] = ...,
  145. option: Optional[int] = ...,
  146. ) -> bytes: ...
  147. ```
  148. `dumps()` serializes Python objects to JSON.
  149. It natively serializes
  150. `str`, `dict`, `list`, `tuple`, `int`, `float`, `bool`, `None`,
  151. `dataclasses.dataclass`, `typing.TypedDict`, `datetime.datetime`,
  152. `datetime.date`, `datetime.time`, `uuid.UUID`, `numpy.ndarray`, and
  153. `orjson.Fragment` instances. It supports arbitrary types through `default`. It
  154. serializes subclasses of `str`, `int`, `dict`, `list`,
  155. `dataclasses.dataclass`, and `enum.Enum`. It does not serialize subclasses
  156. of `tuple` to avoid serializing `namedtuple` objects as arrays. To avoid
  157. serializing subclasses, specify the option `orjson.OPT_PASSTHROUGH_SUBCLASS`.
  158. The output is a `bytes` object containing UTF-8.
  159. The global interpreter lock (GIL) is held for the duration of the call.
  160. It raises `JSONEncodeError` on an unsupported type. This exception message
  161. describes the invalid object with the error message
  162. `Type is not JSON serializable: ...`. To fix this, specify
  163. [default](https://github.com/ijl/orjson?tab=readme-ov-file#default).
  164. It raises `JSONEncodeError` on a `str` that contains invalid UTF-8.
  165. It raises `JSONEncodeError` on an integer that exceeds 64 bits by default or,
  166. with `OPT_STRICT_INTEGER`, 53 bits.
  167. It raises `JSONEncodeError` if a `dict` has a key of a type other than `str`,
  168. unless `OPT_NON_STR_KEYS` is specified.
  169. It raises `JSONEncodeError` if the output of `default` recurses to handling by
  170. `default` more than 254 levels deep.
  171. It raises `JSONEncodeError` on circular references.
  172. It raises `JSONEncodeError` if a `tzinfo` on a datetime object is
  173. unsupported.
  174. `JSONEncodeError` is a subclass of `TypeError`. This is for compatibility
  175. with the standard library.
  176. If the failure was caused by an exception in `default` then
  177. `JSONEncodeError` chains the original exception as `__cause__`.
  178. #### default
  179. To serialize a subclass or arbitrary types, specify `default` as a
  180. callable that returns a supported type. `default` may be a function,
  181. lambda, or callable class instance. To specify that a type was not
  182. handled by `default`, raise an exception such as `TypeError`.
  183. ```python
  184. >>> import orjson, decimal
  185. >>>
  186. def default(obj):
  187. if isinstance(obj, decimal.Decimal):
  188. return str(obj)
  189. raise TypeError
  190. >>> orjson.dumps(decimal.Decimal("0.0842389659712649442845"))
  191. JSONEncodeError: Type is not JSON serializable: decimal.Decimal
  192. >>> orjson.dumps(decimal.Decimal("0.0842389659712649442845"), default=default)
  193. b'"0.0842389659712649442845"'
  194. >>> orjson.dumps({1, 2}, default=default)
  195. orjson.JSONEncodeError: Type is not JSON serializable: set
  196. ```
  197. The `default` callable may return an object that itself
  198. must be handled by `default` up to 254 times before an exception
  199. is raised.
  200. It is important that `default` raise an exception if a type cannot be handled.
  201. Python otherwise implicitly returns `None`, which appears to the caller
  202. like a legitimate value and is serialized:
  203. ```python
  204. >>> import orjson, json
  205. >>>
  206. def default(obj):
  207. if isinstance(obj, decimal.Decimal):
  208. return str(obj)
  209. >>> orjson.dumps({"set":{1, 2}}, default=default)
  210. b'{"set":null}'
  211. >>> json.dumps({"set":{1, 2}}, default=default)
  212. '{"set":null}'
  213. ```
  214. #### option
  215. To modify how data is serialized, specify `option`. Each `option` is an integer
  216. constant in `orjson`. To specify multiple options, mask them together, e.g.,
  217. `option=orjson.OPT_STRICT_INTEGER | orjson.OPT_NAIVE_UTC`.
  218. ##### OPT_APPEND_NEWLINE
  219. Append `\n` to the output. This is a convenience and optimization for the
  220. pattern of `dumps(...) + "\n"`. `bytes` objects are immutable and this
  221. pattern copies the original contents.
  222. ```python
  223. >>> import orjson
  224. >>> orjson.dumps([])
  225. b"[]"
  226. >>> orjson.dumps([], option=orjson.OPT_APPEND_NEWLINE)
  227. b"[]\n"
  228. ```
  229. ##### OPT_INDENT_2
  230. Pretty-print output with an indent of two spaces. This is equivalent to
  231. `indent=2` in the standard library. Pretty printing is slower and the output
  232. larger. This option is compatible with all other options.
  233. ```python
  234. >>> import orjson
  235. >>> orjson.dumps({"a": "b", "c": {"d": True}, "e": [1, 2]})
  236. b'{"a":"b","c":{"d":true},"e":[1,2]}'
  237. >>> orjson.dumps(
  238. {"a": "b", "c": {"d": True}, "e": [1, 2]},
  239. option=orjson.OPT_INDENT_2
  240. )
  241. b'{\n "a": "b",\n "c": {\n "d": true\n },\n "e": [\n 1,\n 2\n ]\n}'
  242. ```
  243. If displayed, the indentation and linebreaks appear like this:
  244. ```json
  245. {
  246. "a": "b",
  247. "c": {
  248. "d": true
  249. },
  250. "e": [
  251. 1,
  252. 2
  253. ]
  254. }
  255. ```
  256. This measures serializing the github.json fixture as compact (52KiB) or
  257. pretty (64KiB):
  258. | Library | compact (ms) | pretty (ms) | vs. orjson |
  259. |-----------|----------------|---------------|--------------|
  260. | orjson | 0.01 | 0.02 | 1 |
  261. | json | 0.13 | 0.54 | 34 |
  262. This measures serializing the citm_catalog.json fixture, more of a worst
  263. case due to the amount of nesting and newlines, as compact (489KiB) or
  264. pretty (1.1MiB):
  265. | Library | compact (ms) | pretty (ms) | vs. orjson |
  266. |-----------|----------------|---------------|--------------|
  267. | orjson | 0.25 | 0.45 | 1 |
  268. | json | 3.01 | 24.42 | 54.4 |
  269. This can be reproduced using the `pyindent` script.
  270. ##### OPT_NAIVE_UTC
  271. Serialize `datetime.datetime` objects without a `tzinfo` as UTC. This
  272. has no effect on `datetime.datetime` objects that have `tzinfo` set.
  273. ```python
  274. >>> import orjson, datetime
  275. >>> orjson.dumps(
  276. datetime.datetime(1970, 1, 1, 0, 0, 0),
  277. )
  278. b'"1970-01-01T00:00:00"'
  279. >>> orjson.dumps(
  280. datetime.datetime(1970, 1, 1, 0, 0, 0),
  281. option=orjson.OPT_NAIVE_UTC,
  282. )
  283. b'"1970-01-01T00:00:00+00:00"'
  284. ```
  285. ##### OPT_NON_STR_KEYS
  286. Serialize `dict` keys of type other than `str`. This allows `dict` keys
  287. to be one of `str`, `int`, `float`, `bool`, `None`, `datetime.datetime`,
  288. `datetime.date`, `datetime.time`, `enum.Enum`, and `uuid.UUID`. For comparison,
  289. the standard library serializes `str`, `int`, `float`, `bool` or `None` by
  290. default. orjson benchmarks as being faster at serializing non-`str` keys
  291. than other libraries. This option is slower for `str` keys than the default.
  292. ```python
  293. >>> import orjson, datetime, uuid
  294. >>> orjson.dumps(
  295. {uuid.UUID("7202d115-7ff3-4c81-a7c1-2a1f067b1ece"): [1, 2, 3]},
  296. option=orjson.OPT_NON_STR_KEYS,
  297. )
  298. b'{"7202d115-7ff3-4c81-a7c1-2a1f067b1ece":[1,2,3]}'
  299. >>> orjson.dumps(
  300. {datetime.datetime(1970, 1, 1, 0, 0, 0): [1, 2, 3]},
  301. option=orjson.OPT_NON_STR_KEYS | orjson.OPT_NAIVE_UTC,
  302. )
  303. b'{"1970-01-01T00:00:00+00:00":[1,2,3]}'
  304. ```
  305. These types are generally serialized how they would be as
  306. values, e.g., `datetime.datetime` is still an RFC 3339 string and respects
  307. options affecting it. The exception is that `int` serialization does not
  308. respect `OPT_STRICT_INTEGER`.
  309. This option has the risk of creating duplicate keys. This is because non-`str`
  310. objects may serialize to the same `str` as an existing key, e.g.,
  311. `{"1": true, 1: false}`. The last key to be inserted to the `dict` will be
  312. serialized last and a JSON deserializer will presumably take the last
  313. occurrence of a key (in the above, `false`). The first value will be lost.
  314. This option is compatible with `orjson.OPT_SORT_KEYS`. If sorting is used,
  315. note the sort is unstable and will be unpredictable for duplicate keys.
  316. ```python
  317. >>> import orjson, datetime
  318. >>> orjson.dumps(
  319. {"other": 1, datetime.date(1970, 1, 5): 2, datetime.date(1970, 1, 3): 3},
  320. option=orjson.OPT_NON_STR_KEYS | orjson.OPT_SORT_KEYS
  321. )
  322. b'{"1970-01-03":3,"1970-01-05":2,"other":1}'
  323. ```
  324. This measures serializing 589KiB of JSON comprising a `list` of 100 `dict`
  325. in which each `dict` has both 365 randomly-sorted `int` keys representing epoch
  326. timestamps as well as one `str` key and the value for each key is a
  327. single integer. In "str keys", the keys were converted to `str` before
  328. serialization, and orjson still specifes `option=orjson.OPT_NON_STR_KEYS`
  329. (which is always somewhat slower).
  330. | Library | str keys (ms) | int keys (ms) | int keys sorted (ms) |
  331. |-----------|-----------------|-----------------|------------------------|
  332. | orjson | 0.5 | 0.93 | 2.08 |
  333. | json | 2.72 | 3.59 | |
  334. json is blank because it
  335. raises `TypeError` on attempting to sort before converting all keys to `str`.
  336. This can be reproduced using the `pynonstr` script.
  337. ##### OPT_OMIT_MICROSECONDS
  338. Do not serialize the `microsecond` field on `datetime.datetime` and
  339. `datetime.time` instances.
  340. ```python
  341. >>> import orjson, datetime
  342. >>> orjson.dumps(
  343. datetime.datetime(1970, 1, 1, 0, 0, 0, 1),
  344. )
  345. b'"1970-01-01T00:00:00.000001"'
  346. >>> orjson.dumps(
  347. datetime.datetime(1970, 1, 1, 0, 0, 0, 1),
  348. option=orjson.OPT_OMIT_MICROSECONDS,
  349. )
  350. b'"1970-01-01T00:00:00"'
  351. ```
  352. ##### OPT_PASSTHROUGH_DATACLASS
  353. Passthrough `dataclasses.dataclass` instances to `default`. This allows
  354. customizing their output but is much slower.
  355. ```python
  356. >>> import orjson, dataclasses
  357. >>>
  358. @dataclasses.dataclass
  359. class User:
  360. id: str
  361. name: str
  362. password: str
  363. def default(obj):
  364. if isinstance(obj, User):
  365. return {"id": obj.id, "name": obj.name}
  366. raise TypeError
  367. >>> orjson.dumps(User("3b1", "asd", "zxc"))
  368. b'{"id":"3b1","name":"asd","password":"zxc"}'
  369. >>> orjson.dumps(User("3b1", "asd", "zxc"), option=orjson.OPT_PASSTHROUGH_DATACLASS)
  370. TypeError: Type is not JSON serializable: User
  371. >>> orjson.dumps(
  372. User("3b1", "asd", "zxc"),
  373. option=orjson.OPT_PASSTHROUGH_DATACLASS,
  374. default=default,
  375. )
  376. b'{"id":"3b1","name":"asd"}'
  377. ```
  378. ##### OPT_PASSTHROUGH_DATETIME
  379. Passthrough `datetime.datetime`, `datetime.date`, and `datetime.time` instances
  380. to `default`. This allows serializing datetimes to a custom format, e.g.,
  381. HTTP dates:
  382. ```python
  383. >>> import orjson, datetime
  384. >>>
  385. def default(obj):
  386. if isinstance(obj, datetime.datetime):
  387. return obj.strftime("%a, %d %b %Y %H:%M:%S GMT")
  388. raise TypeError
  389. >>> orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)})
  390. b'{"created_at":"1970-01-01T00:00:00"}'
  391. >>> orjson.dumps({"created_at": datetime.datetime(1970, 1, 1)}, option=orjson.OPT_PASSTHROUGH_DATETIME)
  392. TypeError: Type is not JSON serializable: datetime.datetime
  393. >>> orjson.dumps(
  394. {"created_at": datetime.datetime(1970, 1, 1)},
  395. option=orjson.OPT_PASSTHROUGH_DATETIME,
  396. default=default,
  397. )
  398. b'{"created_at":"Thu, 01 Jan 1970 00:00:00 GMT"}'
  399. ```
  400. This does not affect datetimes in `dict` keys if using OPT_NON_STR_KEYS.
  401. ##### OPT_PASSTHROUGH_SUBCLASS
  402. Passthrough subclasses of builtin types to `default`.
  403. ```python
  404. >>> import orjson
  405. >>>
  406. class Secret(str):
  407. pass
  408. def default(obj):
  409. if isinstance(obj, Secret):
  410. return "******"
  411. raise TypeError
  412. >>> orjson.dumps(Secret("zxc"))
  413. b'"zxc"'
  414. >>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS)
  415. TypeError: Type is not JSON serializable: Secret
  416. >>> orjson.dumps(Secret("zxc"), option=orjson.OPT_PASSTHROUGH_SUBCLASS, default=default)
  417. b'"******"'
  418. ```
  419. This does not affect serializing subclasses as `dict` keys if using
  420. OPT_NON_STR_KEYS.
  421. ##### OPT_SERIALIZE_DATACLASS
  422. This is deprecated and has no effect in version 3. In version 2 this was
  423. required to serialize `dataclasses.dataclass` instances. For more, see
  424. [dataclass](https://github.com/ijl/orjson?tab=readme-ov-file#dataclass).
  425. ##### OPT_SERIALIZE_NUMPY
  426. Serialize `numpy.ndarray` instances. For more, see
  427. [numpy](https://github.com/ijl/orjson?tab=readme-ov-file#numpy).
  428. ##### OPT_SERIALIZE_UUID
  429. This is deprecated and has no effect in version 3. In version 2 this was
  430. required to serialize `uuid.UUID` instances. For more, see
  431. [UUID](https://github.com/ijl/orjson?tab=readme-ov-file#UUID).
  432. ##### OPT_SORT_KEYS
  433. Serialize `dict` keys in sorted order. The default is to serialize in an
  434. unspecified order. This is equivalent to `sort_keys=True` in the standard
  435. library.
  436. This can be used to ensure the order is deterministic for hashing or tests.
  437. It has a substantial performance penalty and is not recommended in general.
  438. ```python
  439. >>> import orjson
  440. >>> orjson.dumps({"b": 1, "c": 2, "a": 3})
  441. b'{"b":1,"c":2,"a":3}'
  442. >>> orjson.dumps({"b": 1, "c": 2, "a": 3}, option=orjson.OPT_SORT_KEYS)
  443. b'{"a":3,"b":1,"c":2}'
  444. ```
  445. This measures serializing the twitter.json fixture unsorted and sorted:
  446. | Library | unsorted (ms) | sorted (ms) | vs. orjson |
  447. |-----------|-----------------|---------------|--------------|
  448. | orjson | 0.11 | 0.3 | 1 |
  449. | json | 1.36 | 1.93 | 6.4 |
  450. The benchmark can be reproduced using the `pysort` script.
  451. The sorting is not collation/locale-aware:
  452. ```python
  453. >>> import orjson
  454. >>> orjson.dumps({"a": 1, "ä": 2, "A": 3}, option=orjson.OPT_SORT_KEYS)
  455. b'{"A":3,"a":1,"\xc3\xa4":2}'
  456. ```
  457. This is the same sorting behavior as the standard library.
  458. `dataclass` also serialize as maps but this has no effect on them.
  459. ##### OPT_STRICT_INTEGER
  460. Enforce 53-bit limit on integers. The limit is otherwise 64 bits, the same as
  461. the Python standard library. For more, see [int](https://github.com/ijl/orjson?tab=readme-ov-file#int).
  462. ##### OPT_UTC_Z
  463. Serialize a UTC timezone on `datetime.datetime` instances as `Z` instead
  464. of `+00:00`.
  465. ```python
  466. >>> import orjson, datetime, zoneinfo
  467. >>> orjson.dumps(
  468. datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")),
  469. )
  470. b'"1970-01-01T00:00:00+00:00"'
  471. >>> orjson.dumps(
  472. datetime.datetime(1970, 1, 1, 0, 0, 0, tzinfo=zoneinfo.ZoneInfo("UTC")),
  473. option=orjson.OPT_UTC_Z
  474. )
  475. b'"1970-01-01T00:00:00Z"'
  476. ```
  477. #### Fragment
  478. `orjson.Fragment` includes already-serialized JSON in a document. This is an
  479. efficient way to include JSON blobs from a cache, JSONB field, or separately
  480. serialized object without first deserializing to Python objects via `loads()`.
  481. ```python
  482. >>> import orjson
  483. >>> orjson.dumps({"key": "zxc", "data": orjson.Fragment(b'{"a": "b", "c": 1}')})
  484. b'{"key":"zxc","data":{"a": "b", "c": 1}}'
  485. ```
  486. It does no reformatting: `orjson.OPT_INDENT_2` will not affect a
  487. compact blob nor will a pretty-printed JSON blob be rewritten as compact.
  488. The input must be `bytes` or `str` and given as a positional argument.
  489. This raises `orjson.JSONEncodeError` if a `str` is given and the input is
  490. not valid UTF-8. It otherwise does no validation and it is possible to
  491. write invalid JSON. This does not escape characters. The implementation is
  492. tested to not crash if given invalid strings or invalid JSON.
  493. ### Deserialize
  494. ```python
  495. def loads(__obj: Union[bytes, bytearray, memoryview, str]) -> Any: ...
  496. ```
  497. `loads()` deserializes JSON to Python objects. It deserializes to `dict`,
  498. `list`, `int`, `float`, `str`, `bool`, and `None` objects.
  499. `bytes`, `bytearray`, `memoryview`, and `str` input are accepted. If the input
  500. exists as a `memoryview`, `bytearray`, or `bytes` object, it is recommended to
  501. pass these directly rather than creating an unnecessary `str` object. That is,
  502. `orjson.loads(b"{}")` instead of `orjson.loads(b"{}".decode("utf-8"))`. This
  503. has lower memory usage and lower latency.
  504. The input must be valid UTF-8.
  505. orjson maintains a cache of map keys for the duration of the process. This
  506. causes a net reduction in memory usage by avoiding duplicate strings. The
  507. keys must be at most 64 bytes to be cached and 2048 entries are stored.
  508. The global interpreter lock (GIL) is held for the duration of the call.
  509. It raises `JSONDecodeError` if given an invalid type or invalid
  510. JSON. This includes if the input contains `NaN`, `Infinity`, or `-Infinity`,
  511. which the standard library allows, but is not valid JSON.
  512. It raises `JSONDecodeError` if a combination of array or object recurses
  513. 1024 levels deep.
  514. It raises `JSONDecodeError` if unable to allocate a buffer large enough
  515. to parse the document.
  516. `JSONDecodeError` is a subclass of `json.JSONDecodeError` and `ValueError`.
  517. This is for compatibility with the standard library.
  518. ## Types
  519. ### dataclass
  520. orjson serializes instances of `dataclasses.dataclass` natively. It serializes
  521. instances 40-50x as fast as other libraries and avoids a severe slowdown seen
  522. in other libraries compared to serializing `dict`.
  523. It is supported to pass all variants of dataclasses, including dataclasses
  524. using `__slots__`, frozen dataclasses, those with optional or default
  525. attributes, and subclasses. There is a performance benefit to not
  526. using `__slots__`.
  527. | Library | dict (ms) | dataclass (ms) | vs. orjson |
  528. |-----------|-------------|------------------|--------------|
  529. | orjson | 0.43 | 0.95 | 1 |
  530. | json | 5.81 | 38.32 | 40 |
  531. This measures serializing 555KiB of JSON, orjson natively and other libraries
  532. using `default` to serialize the output of `dataclasses.asdict()`. This can be
  533. reproduced using the `pydataclass` script.
  534. Dataclasses are serialized as maps, with every attribute serialized and in
  535. the order given on class definition:
  536. ```python
  537. >>> import dataclasses, orjson, typing
  538. @dataclasses.dataclass
  539. class Member:
  540. id: int
  541. active: bool = dataclasses.field(default=False)
  542. @dataclasses.dataclass
  543. class Object:
  544. id: int
  545. name: str
  546. members: typing.List[Member]
  547. >>> orjson.dumps(Object(1, "a", [Member(1, True), Member(2)]))
  548. b'{"id":1,"name":"a","members":[{"id":1,"active":true},{"id":2,"active":false}]}'
  549. ```
  550. ### datetime
  551. orjson serializes `datetime.datetime` objects to
  552. [RFC 3339](https://tools.ietf.org/html/rfc3339) format,
  553. e.g., "1970-01-01T00:00:00+00:00". This is a subset of ISO 8601 and is
  554. compatible with `isoformat()` in the standard library.
  555. ```python
  556. >>> import orjson, datetime, zoneinfo
  557. >>> orjson.dumps(
  558. datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=zoneinfo.ZoneInfo("Australia/Adelaide"))
  559. )
  560. b'"2018-12-01T02:03:04.000009+10:30"'
  561. >>> orjson.dumps(
  562. datetime.datetime(2100, 9, 1, 21, 55, 2).replace(tzinfo=zoneinfo.ZoneInfo("UTC"))
  563. )
  564. b'"2100-09-01T21:55:02+00:00"'
  565. >>> orjson.dumps(
  566. datetime.datetime(2100, 9, 1, 21, 55, 2)
  567. )
  568. b'"2100-09-01T21:55:02"'
  569. ```
  570. `datetime.datetime` supports instances with a `tzinfo` that is `None`,
  571. `datetime.timezone.utc`, a timezone instance from the python3.9+ `zoneinfo`
  572. module, or a timezone instance from the third-party `pendulum`, `pytz`, or
  573. `dateutil`/`arrow` libraries.
  574. It is fastest to use the standard library's `zoneinfo.ZoneInfo` for timezones.
  575. `datetime.time` objects must not have a `tzinfo`.
  576. ```python
  577. >>> import orjson, datetime
  578. >>> orjson.dumps(datetime.time(12, 0, 15, 290))
  579. b'"12:00:15.000290"'
  580. ```
  581. `datetime.date` objects will always serialize.
  582. ```python
  583. >>> import orjson, datetime
  584. >>> orjson.dumps(datetime.date(1900, 1, 2))
  585. b'"1900-01-02"'
  586. ```
  587. Errors with `tzinfo` result in `JSONEncodeError` being raised.
  588. To disable serialization of `datetime` objects specify the option
  589. `orjson.OPT_PASSTHROUGH_DATETIME`.
  590. To use "Z" suffix instead of "+00:00" to indicate UTC ("Zulu") time, use the option
  591. `orjson.OPT_UTC_Z`.
  592. To assume datetimes without timezone are UTC, use the option `orjson.OPT_NAIVE_UTC`.
  593. ### enum
  594. orjson serializes enums natively. Options apply to their values.
  595. ```python
  596. >>> import enum, datetime, orjson
  597. >>>
  598. class DatetimeEnum(enum.Enum):
  599. EPOCH = datetime.datetime(1970, 1, 1, 0, 0, 0)
  600. >>> orjson.dumps(DatetimeEnum.EPOCH)
  601. b'"1970-01-01T00:00:00"'
  602. >>> orjson.dumps(DatetimeEnum.EPOCH, option=orjson.OPT_NAIVE_UTC)
  603. b'"1970-01-01T00:00:00+00:00"'
  604. ```
  605. Enums with members that are not supported types can be serialized using
  606. `default`:
  607. ```python
  608. >>> import enum, orjson
  609. >>>
  610. class Custom:
  611. def __init__(self, val):
  612. self.val = val
  613. def default(obj):
  614. if isinstance(obj, Custom):
  615. return obj.val
  616. raise TypeError
  617. class CustomEnum(enum.Enum):
  618. ONE = Custom(1)
  619. >>> orjson.dumps(CustomEnum.ONE, default=default)
  620. b'1'
  621. ```
  622. ### float
  623. orjson serializes and deserializes double precision floats with no loss of
  624. precision and consistent rounding.
  625. `orjson.dumps()` serializes Nan, Infinity, and -Infinity, which are not
  626. compliant JSON, as `null`:
  627. ```python
  628. >>> import orjson, json
  629. >>> orjson.dumps([float("NaN"), float("Infinity"), float("-Infinity")])
  630. b'[null,null,null]'
  631. >>> json.dumps([float("NaN"), float("Infinity"), float("-Infinity")])
  632. '[NaN, Infinity, -Infinity]'
  633. ```
  634. ### int
  635. orjson serializes and deserializes 64-bit integers by default. The range
  636. supported is a signed 64-bit integer's minimum (-9223372036854775807) to
  637. an unsigned 64-bit integer's maximum (18446744073709551615). This
  638. is widely compatible, but there are implementations
  639. that only support 53-bits for integers, e.g.,
  640. web browsers. For those implementations, `dumps()` can be configured to
  641. raise a `JSONEncodeError` on values exceeding the 53-bit range.
  642. ```python
  643. >>> import orjson
  644. >>> orjson.dumps(9007199254740992)
  645. b'9007199254740992'
  646. >>> orjson.dumps(9007199254740992, option=orjson.OPT_STRICT_INTEGER)
  647. JSONEncodeError: Integer exceeds 53-bit range
  648. >>> orjson.dumps(-9007199254740992, option=orjson.OPT_STRICT_INTEGER)
  649. JSONEncodeError: Integer exceeds 53-bit range
  650. ```
  651. ### numpy
  652. orjson natively serializes `numpy.ndarray` and individual
  653. `numpy.float64`, `numpy.float32`, `numpy.float16` (`numpy.half`),
  654. `numpy.int64`, `numpy.int32`, `numpy.int16`, `numpy.int8`,
  655. `numpy.uint64`, `numpy.uint32`, `numpy.uint16`, `numpy.uint8`,
  656. `numpy.uintp`, `numpy.intp`, `numpy.datetime64`, and `numpy.bool`
  657. instances.
  658. orjson is compatible with both numpy v1 and v2.
  659. orjson is faster than all compared libraries at serializing
  660. numpy instances. Serializing numpy data requires specifying
  661. `option=orjson.OPT_SERIALIZE_NUMPY`.
  662. ```python
  663. >>> import orjson, numpy
  664. >>> orjson.dumps(
  665. numpy.array([[1, 2, 3], [4, 5, 6]]),
  666. option=orjson.OPT_SERIALIZE_NUMPY,
  667. )
  668. b'[[1,2,3],[4,5,6]]'
  669. ```
  670. The array must be a contiguous C array (`C_CONTIGUOUS`) and one of the
  671. supported datatypes.
  672. Note a difference between serializing `numpy.float32` using `ndarray.tolist()`
  673. or `orjson.dumps(..., option=orjson.OPT_SERIALIZE_NUMPY)`: `tolist()` converts
  674. to a `double` before serializing and orjson's native path does not. This
  675. can result in different rounding.
  676. `numpy.datetime64` instances are serialized as RFC 3339 strings and
  677. datetime options affect them.
  678. ```python
  679. >>> import orjson, numpy
  680. >>> orjson.dumps(
  681. numpy.datetime64("2021-01-01T00:00:00.172"),
  682. option=orjson.OPT_SERIALIZE_NUMPY,
  683. )
  684. b'"2021-01-01T00:00:00.172000"'
  685. >>> orjson.dumps(
  686. numpy.datetime64("2021-01-01T00:00:00.172"),
  687. option=(
  688. orjson.OPT_SERIALIZE_NUMPY |
  689. orjson.OPT_NAIVE_UTC |
  690. orjson.OPT_OMIT_MICROSECONDS
  691. ),
  692. )
  693. b'"2021-01-01T00:00:00+00:00"'
  694. ```
  695. If an array is not a contiguous C array, contains an unsupported datatype,
  696. or contains a `numpy.datetime64` using an unsupported representation
  697. (e.g., picoseconds), orjson falls through to `default`. In `default`,
  698. `obj.tolist()` can be specified.
  699. If an array is not in the native endianness, e.g., an array of big-endian values
  700. on a little-endian system, `orjson.JSONEncodeError` is raised.
  701. If an array is malformed, `orjson.JSONEncodeError` is raised.
  702. This measures serializing 92MiB of JSON from an `numpy.ndarray` with
  703. dimensions of `(50000, 100)` and `numpy.float64` values:
  704. | Library | Latency (ms) | RSS diff (MiB) | vs. orjson |
  705. |-----------|----------------|------------------|--------------|
  706. | orjson | 105 | 105 | 1 |
  707. | json | 1,481 | 295 | 14.2 |
  708. This measures serializing 100MiB of JSON from an `numpy.ndarray` with
  709. dimensions of `(100000, 100)` and `numpy.int32` values:
  710. | Library | Latency (ms) | RSS diff (MiB) | vs. orjson |
  711. |-----------|----------------|------------------|--------------|
  712. | orjson | 68 | 119 | 1 |
  713. | json | 684 | 501 | 10.1 |
  714. This measures serializing 105MiB of JSON from an `numpy.ndarray` with
  715. dimensions of `(100000, 200)` and `numpy.bool` values:
  716. | Library | Latency (ms) | RSS diff (MiB) | vs. orjson |
  717. |-----------|----------------|------------------|--------------|
  718. | orjson | 50 | 125 | 1 |
  719. | json | 573 | 398 | 11.5 |
  720. In these benchmarks, orjson serializes natively and `json` serializes
  721. `ndarray.tolist()` via `default`. The RSS column measures peak memory
  722. usage during serialization. This can be reproduced using the `pynumpy` script.
  723. orjson does not have an installation or compilation dependency on numpy. The
  724. implementation is independent, reading `numpy.ndarray` using
  725. `PyArrayInterface`.
  726. ### str
  727. orjson is strict about UTF-8 conformance. This is stricter than the standard
  728. library's json module, which will serialize and deserialize UTF-16 surrogates,
  729. e.g., "\ud800", that are invalid UTF-8.
  730. If `orjson.dumps()` is given a `str` that does not contain valid UTF-8,
  731. `orjson.JSONEncodeError` is raised. If `loads()` receives invalid UTF-8,
  732. `orjson.JSONDecodeError` is raised.
  733. ```python
  734. >>> import orjson, json
  735. >>> orjson.dumps('\ud800')
  736. JSONEncodeError: str is not valid UTF-8: surrogates not allowed
  737. >>> json.dumps('\ud800')
  738. '"\\ud800"'
  739. >>> orjson.loads('"\\ud800"')
  740. JSONDecodeError: unexpected end of hex escape at line 1 column 8: line 1 column 1 (char 0)
  741. >>> json.loads('"\\ud800"')
  742. '\ud800'
  743. ```
  744. To make a best effort at deserializing bad input, first decode `bytes` using
  745. the `replace` or `lossy` argument for `errors`:
  746. ```python
  747. >>> import orjson
  748. >>> orjson.loads(b'"\xed\xa0\x80"')
  749. JSONDecodeError: str is not valid UTF-8: surrogates not allowed
  750. >>> orjson.loads(b'"\xed\xa0\x80"'.decode("utf-8", "replace"))
  751. '���'
  752. ```
  753. ### uuid
  754. orjson serializes `uuid.UUID` instances to
  755. [RFC 4122](https://tools.ietf.org/html/rfc4122) format, e.g.,
  756. "f81d4fae-7dec-11d0-a765-00a0c91e6bf6".
  757. ``` python
  758. >>> import orjson, uuid
  759. >>> orjson.dumps(uuid.uuid5(uuid.NAMESPACE_DNS, "python.org"))
  760. b'"886313e1-3b8a-5372-9b90-0c9aee199e5d"'
  761. ```
  762. ## Testing
  763. The library has comprehensive tests. There are tests against fixtures in the
  764. [JSONTestSuite](https://github.com/nst/JSONTestSuite) and
  765. [nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark)
  766. repositories. It is tested to not crash against the
  767. [Big List of Naughty Strings](https://github.com/minimaxir/big-list-of-naughty-strings).
  768. It is tested to not leak memory. It is tested to not crash
  769. against and not accept invalid UTF-8. There are integration tests
  770. exercising the library's use in web servers (gunicorn using multiprocess/forked
  771. workers) and when multithreaded.
  772. orjson is the most correct of the compared libraries. This graph shows how each
  773. library handles a combined 342 JSON fixtures from the
  774. [JSONTestSuite](https://github.com/nst/JSONTestSuite) and
  775. [nativejson-benchmark](https://github.com/miloyip/nativejson-benchmark) tests:
  776. | Library | Invalid JSON documents not rejected | Valid JSON documents not deserialized |
  777. |------------|---------------------------------------|-----------------------------------------|
  778. | orjson | 0 | 0 |
  779. | json | 17 | 0 |
  780. This shows that all libraries deserialize valid JSON but only orjson
  781. correctly rejects the given invalid JSON fixtures. Errors are largely due to
  782. accepting invalid strings and numbers.
  783. The graph above can be reproduced using the `pycorrectness` script.
  784. ## Performance
  785. Serialization and deserialization performance of orjson is consistently better
  786. than the standard library's `json`. The graphs below illustrate a few commonly
  787. used documents.
  788. ### Latency
  789. ![Serialization](doc/serialization.png)
  790. ![Deserialization](doc/deserialization.png)
  791. #### twitter.json serialization
  792. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  793. |-----------|---------------------------------|-------------------------|----------------------|
  794. | orjson | 0.1 | 8453 | 1 |
  795. | json | 1.3 | 765 | 11.1 |
  796. #### twitter.json deserialization
  797. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  798. |-----------|---------------------------------|-------------------------|----------------------|
  799. | orjson | 0.5 | 1889 | 1 |
  800. | json | 2.2 | 453 | 4.2 |
  801. #### github.json serialization
  802. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  803. |-----------|---------------------------------|-------------------------|----------------------|
  804. | orjson | 0.01 | 103693 | 1 |
  805. | json | 0.13 | 7648 | 13.6 |
  806. #### github.json deserialization
  807. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  808. |-----------|---------------------------------|-------------------------|----------------------|
  809. | orjson | 0.04 | 23264 | 1 |
  810. | json | 0.1 | 10430 | 2.2 |
  811. #### citm_catalog.json serialization
  812. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  813. |-----------|---------------------------------|-------------------------|----------------------|
  814. | orjson | 0.3 | 3975 | 1 |
  815. | json | 3 | 338 | 11.8 |
  816. #### citm_catalog.json deserialization
  817. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  818. |-----------|---------------------------------|-------------------------|----------------------|
  819. | orjson | 1.3 | 781 | 1 |
  820. | json | 4 | 250 | 3.1 |
  821. #### canada.json serialization
  822. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  823. |-----------|---------------------------------|-------------------------|----------------------|
  824. | orjson | 2.5 | 399 | 1 |
  825. | json | 29.8 | 33 | 11.9 |
  826. #### canada.json deserialization
  827. | Library | Median latency (milliseconds) | Operations per second | Relative (latency) |
  828. |-----------|---------------------------------|-------------------------|----------------------|
  829. | orjson | 3 | 333 | 1 |
  830. | json | 18 | 55 | 6 |
  831. ### Reproducing
  832. The above was measured using Python 3.11.10 in a Fedora 42 container on an
  833. x86-64-v4 machine using the
  834. `orjson-3.10.11-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl`
  835. artifact on PyPI. The latency results can be reproduced using the `pybench` script.
  836. ## Questions
  837. ### Will it deserialize to dataclasses, UUIDs, decimals, etc or support object_hook?
  838. No. This requires a schema specifying what types are expected and how to
  839. handle errors etc. This is addressed by data validation libraries a
  840. level above this.
  841. ### Will it serialize to `str`?
  842. No. `bytes` is the correct type for a serialized blob.
  843. ### Will it support NDJSON or JSONL?
  844. No. [orjsonl](https://github.com/umarbutler/orjsonl) may be appropriate.
  845. ### Will it support JSON5 or RJSON?
  846. No, it supports RFC 8259.
  847. ### How do I depend on orjson in a Rust project?
  848. orjson is only shipped as a Python module. The project should depend on
  849. `orjson` in its own Python requirements and should obtain pointers to
  850. functions and objects using the normal `PyImport_*` APIs.
  851. ## Packaging
  852. To package orjson requires at least [Rust](https://www.rust-lang.org/) 1.85,
  853. a C compiler, and the [maturin](https://github.com/PyO3/maturin) build tool.
  854. The recommended build command is:
  855. ```sh
  856. maturin build --release --strip
  857. ```
  858. The project's own CI tests against `nightly-2025-12-01` and stable 1.85. It
  859. is prudent to pin the nightly version because that channel can introduce
  860. breaking changes. There is a significant performance benefit to using
  861. nightly.
  862. orjson is tested on native hardware for amd64, aarch64, and i686 on Linux and
  863. for arm7, ppc64le, and s390x is cross-compiled and may be tested via
  864. emulation. It is tested for aarch64 on macOS and cross-compiles for amd64. For
  865. Windows it is tested on amd64, i686, and aarch64.
  866. There are no runtime dependencies other than libc.
  867. The source distribution on PyPI contains all dependencies' source and can be
  868. built without network access. The file can be downloaded from
  869. `https://files.pythonhosted.org/packages/source/o/orjson/orjson-${version}.tar.gz`.
  870. orjson's tests are included in the source distribution on PyPI. The tests
  871. require only `pytest`. There are optional packages such as `pytz` and `numpy`
  872. listed in `test/requirements.txt` and used in ~10% of tests. Not having these
  873. dependencies causes the tests needing them to skip. Tests can be run
  874. with `pytest -q test`.
  875. ## License
  876. orjson was written by ijl <<ijl@mailbox.org>>, copyright 2018 - 2025, available
  877. to you under either the Apache 2 license or MIT license at your choice.