Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 
 

1148 Zeilen
41 KiB

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