METADATA 41 KB

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