Skip to main content

Fast, correct Python JSON library

Project description

orjson

orjson is a fast, correct JSON library for Python. It benchmarks as the fastest Python library for JSON and has comprehensive unit, integration, and interoperability tests.

Its serialization performance is 2x to 3x the nearest other library and 4x to 12x the standard library. Its deserialization performance is 0.9x to 1.1x the nearest other library and 1.1x to 2x the standard library.

It differs in behavior from other Python JSON libraries in supporting datetimes, not supporting subclasses without a default hook, serializing UTF-8 to bytes rather than escaped ASCII (e.g., "好" rather than "\\u597d") by default, having strict UTF-8 conformance, having strict JSON conformance on NaN/Infinity/-Infinity, having an option for strict JSON conformance on 53-bit integers, not supporting pretty printing, and not supporting all standard library options.

orjson supports CPython 3.5, 3.6, 3.7, and 3.8. It distributes wheels for Linux, macOS, and Windows. It is dual licensed under the Apache 2.0 and MIT licenses. The repository and issue tracker is github.com/ijl/orjson, and patches may be submitted there.

Usage

Install

To install a wheel from PyPI:

pip install --upgrade orjson

To build a release wheel from source, assuming a Rust nightly toolchain and Python environment:

git clone https://github.com/ijl/orjson.git && cd orjson
pip install --upgrade pyo3-pack
pyo3-pack build --release --strip --interpreter python3.7

There is no runtime dependency other than a manylinux environment (i.e., deploying this does not require Rust or non-libc type libraries.)

Serialize

def dumps(obj: Any, default: Optional[Callable[[Any], Any]], option: Optional[int]) -> bytes: ...

dumps() serializes Python objects to JSON.

It natively serializes str, dict, list, tuple, int, float, datetime.datetime, datetime.date, datetime.time, and None instances. It supports arbitrary types through default. It does not serialize subclasses of supported types natively, but default may be used.

It accepts options via an option keyword argument. These include:

  • orjson.OPT_STRICT_INTEGER for enforcing a 53-bit limit on integers. The limit is otherwise 64 bits, the same as the Python standard library.
  • orjson.OPT_NAIVE_UTC for assuming datetime.datetime objects without a tzinfo are UTC.

To specify multiple options, mask them together, e.g., option=orjson.OPT_STRICT_INTEGER | orjson.OPT_NAIVE_UTC.

It raises JSONEncodeError on an unsupported type. This exception message describes the invalid object.

It raises JSONEncodeError on a str that contains invalid UTF-8.

It raises JSONEncodeError on an integer that exceeds 64 bits by default or, with OPT_STRICT_INTEGER, 53 bits.

It raises JSONEncodeError if a dict has a key of a type other than str.

It raises JSONEncodeError if the output of default recurses to handling by default more than five levels deep.

It raises JSONEncodeError if a tzinfo on a datetime object is incorrect.

JSONEncodeError is a subclass of TypeError. This is for compatibility with the standard library.

import orjson

try:
    val = orjson.dumps(...)
except orjson.JSONEncodeError:
    raise

To serialize arbitrary types, specify default as a callable that returns a supported type. default may be a function, lambda, or callable class instance.

>>> import orjson, numpy
>>> def default(obj):
        if isinstance(obj, numpy.ndarray):
            return obj.tolist()
>>> orjson.dumps(numpy.random.rand(2, 2), default=default)
b'[[0.08423896597867486,0.854121264944197],[0.8452845446981371,0.19227780743524303]]'

If the default callable does not return an object, and an exception was raised within the default function, an exception describing this is raised. If no object is returned by the default callable but also no exception was raised, it falls through to raising JSONEncodeError on an unsupported type.

The default callable may return an object that itself must be handled by default up to five levels deep before an exception is raised.

Deserialize

def loads(obj: Union[bytes, str]) -> Union[dict, list, int, float, str, None]: ...

loads() deserializes JSON to Python objects.

It raises JSONDecodeError if given an invalid type or invalid JSON. This includes if the input contains NaN, Infinity, or -Infinity, which the standard library allows, but is not valid JSON.

JSONDecodeError is a subclass of ValueError. This is for compatibility with the standard library.

import orjson

try:
    val = orjson.loads(...)
except orjson.JSONDecodeError:
    raise

Comparison

There are slight differences in output between libraries. The differences are not an issue for interoperability. Note orjson returns bytes. Its output is slightly smaller as well.

>>> import orjson, ujson, rapidjson, json
>>> data = {'bool': True, '🐈':'哈哈', 'int': 9223372036854775807, 'float': 1.337e+40}
>>> orjson.dumps(data)
b'{"bool":true,"\xf0\x9f\x90\x88":"\xe5\x93\x88\xe5\x93\x88","int":9223372036854775807,"float":1.337e40}'
>>> ujson.dumps(data)
'{"bool":true,"\\ud83d\\udc08":"\\u54c8\\u54c8","int":9223372036854775807,"float":1.337000000000000e+40}'
>>> rapidjson.dumps(data)
'{"bool":true,"\\uD83D\\uDC08":"\\u54C8\\u54C8","int":9223372036854775807,"float":1.337e+40}'
>>> json.dumps(data)
'{"bool": true, "\\ud83d\\udc08": "\\u54c8\\u54c8", "int": 9223372036854775807, "float": 1.337e+40}'

datetime

orjson serializes datetime.datetime objects to RFC 3339 format, a subset of ISO 8601.

datetime.datetime objects serialize with or without a tzinfo. For a full RFC 3339 representation, tzinfo must be present or orjson.OPT_NAIVE_UTC must be specified (e.g., for timestamps stored in a database in UTC and deserialized by the database adapter without a tzinfo). If a tzinfo is not present, a timezone offset is not serialized.

tzinfo, if specified, must be a timezone object that is either datetime.timezone.utc or from the pendulum, pytz, or dateutil/arrow libraries.

>>> import orjson, datetime, pendulum
>>> orjson.dumps(
    datetime.datetime.fromtimestamp(4123518902).replace(tzinfo=datetime.timezone.utc)
)
b'"2100-09-01T21:55:02+00:00"'
>>> orjson.dumps(
    datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=pendulum.timezone('Australia/Adelaide'))
)
b'"2018-12-01T02:03:04.9+10:30"'
>>> orjson.dumps(
    datetime.datetime.fromtimestamp(4123518902)
)
b'"2100-09-01T21:55:02"'

orjson.OPT_NAIVE_UTC, if specified, only applies to objects that do not have a tzinfo.

>>> import orjson, datetime, pendulum
>>> orjson.dumps(
    datetime.datetime.fromtimestamp(4123518902),
    option=orjson.OPT_NAIVE_UTC
)
b'"2100-09-01T21:55:02+00:00"'
>>> orjson.dumps(
    datetime.datetime(2018, 12, 1, 2, 3, 4, 9, tzinfo=pendulum.timezone('Australia/Adelaide')),
    option=orjson.OPT_NAIVE_UTC
)
b'"2018-12-01T02:03:04.9+10:30"'

datetime.time objects must not have a tzinfo.

>>> import orjson, datetime
>>> orjson.dumps(datetime.time(12, 0, 15, 291290))
b'"12:00:15.291290"'

datetime.date objects will always serialize.

>>> import orjson, datetime
>>> orjson.dumps(datetime.date(1900, 1, 2))
b'"1900-01-02"'

Errors with tzinfo result in JSONEncodeError being raised.

It is faster to have orjson serialize datetime objects than to do so before calling dumps(). If using an unsupported type such as pendulum.datetime, use default.

int

JSON only requires that implementations accept integers with 53-bit precision. orjson will, by default, serialize 64-bit integers. This is compatible with the Python standard library and other non-browser implementations. For transmitting JSON to a web browser or other strict implementations, dumps() can be configured to raise a JSONEncodeError on values exceeding the 53-bit range.

>>> import orjson
>>> orjson.dumps(9007199254740992)
b'9007199254740992'
>>> orjson.dumps(9007199254740992, option=orjson.OPT_STRICT_INTEGER)
JSONEncodeError: Integer exceeds 53-bit max
>>> orjson.dumps(-9007199254740992, option=orjson.OPT_STRICT_INTEGER)
JSONEncodeError: Integer exceeds 53-bit max

float

orjson serializes and deserializes float values in a consistent way. The same behavior is observed in rapidjson, simplejson, and json. ujson is inaccurate in both serialization and deserialization.

UTF-8

orjson raises an exception on invalid UTF-8. This is necessary because Python 3 str objects may contain UTF-16 surrogates. The standard library's json module accepts invalid UTF-8.

>>> import orjson, ujson, rapidjson, json
>>> orjson.dumps('\ud800')
JSONEncodeError: str is not valid UTF-8: surrogates not allowed
>>> ujson.dumps('\ud800')
UnicodeEncodeError: 'utf-8' codec ...
>>> rapidjson.dumps('\ud800')
UnicodeEncodeError: 'utf-8' codec ...
>>> json.dumps('\ud800')
'"\\ud800"'
>>> import orjson, ujson, rapidjson, json
>>> orjson.loads('"\\ud800"')
JSONDecodeError: unexpected end of hex escape at line 1 column 8: line 1 column 1 (char 0)
>>> ujson.loads('"\\ud800"')
''
>>> rapidjson.loads('"\\ud800"')
ValueError: Parse error at offset 1: The surrogate pair in string is invalid.
>>> json.loads('"\\ud800"')
'\ud800'

Testing

The library has comprehensive tests. There are unit tests against the roundtrip, jsonchecker, and fixtures files of the nativejson-benchmark repository. It is tested to not crash against the Big List of Naughty Strings. It is tested to not leak memory. It is tested to be correct against input from the PyJFuzz JSON fuzzer. It is tested to not crash against and not accept invalid UTF-8. There are integration tests exercising the library's use in web servers (gunicorn using multiprocess/forked workers) and when multithreaded. It also uses some tests from the ultrajson library.

Performance

Serialization and deserialization performance of orjson is better than ultrajson, rapidjson, simplejson, or json. The benchmarks are done on fixtures of real data:

  • twitter.json, 631.5KiB, results of a search on Twitter for "一", containing CJK strings, dictionaries of strings and arrays of dictionaries, indented.

  • github.json, 55.8KiB, a GitHub activity feed, containing dictionaries of strings and arrays of dictionaries, not indented.

  • citm_catalog.json, 1.7MiB, concert data, containing nested dictionaries of strings and arrays of integers, indented.

  • canada.json, 2.2MiB, coordinates of the Canadian border in GeoJSON format, containing floats and arrays, indented.

alt text alt text alt text alt text alt text alt text alt text alt text

twitter.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.54 1854.5 1
ujson 1.47 678.3 2.73
rapidjson 1.58 634 2.92
simplejson 2.7 369.3 5.01
json 2.45 407.7 4.55

twitter.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 2.6 384.4 1
ujson 2.33 427.2 0.89
rapidjson 3.09 322 1.19
simplejson 2.61 381.5 1
json 2.91 342.1 1.12

github.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.06 16532.4 1
ujson 0.14 6990.6 2.35
rapidjson 0.16 6236.3 2.65
simplejson 0.31 3234.9 5.1
json 0.25 3943.4 4.19

github.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.23 4395.8 1
ujson 0.23 4431.2 0.99
rapidjson 0.27 3746.8 1.18
simplejson 0.22 4652.8 0.95
json 0.25 3991.5 1.11

citm_catalog.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 0.81 1232 1
ujson 2.78 359.1 3.43
rapidjson 2.59 386 3.19
simplejson 10.53 95.2 12.98
json 5.41 184.7 6.67

citm_catalog.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 4.76 210.1 1
ujson 4.39 228 0.92
rapidjson 5.79 174.9 1.22
simplejson 6.1 163.8 1.28
json 6.03 165.7 1.27

canada.json serialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 3.95 252.1 1
ujson
rapidjson 44.17 22.6 11.18
simplejson 64.52 15.5 16.33
json 47.01 21.3 11.9

canada.json deserialization

Library Median latency (milliseconds) Operations per second Relative (latency)
orjson 14.76 67.8 1
ujson
rapidjson 29.01 34.5 1.97
simplejson 26.75 37.4 1.81
json 27.18 36.8 1.84

If a row is blank, the library did not serialize and deserialize the fixture without modifying it, e.g., returning different values for floating point numbers.

This was measured using Python 3.7.3 on Linux with orjson 2.0.5, ujson 1.35, python-rapidson 0.7.0, and simplejson 3.16.0.

The results can be reproduced using the pybench and graph scripts.

Project details


Release history Release notifications | RSS feed

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distributions

No source distribution files available for this release.See tutorial on generating distribution archives.

Built Distributions

If you're not sure about the file name format, learn more about wheel file names.

orjson-2.0.5-cp37-none-win_amd64.whl (156.4 kB view details)

Uploaded CPython 3.7Windows x86-64

orjson-2.0.5-cp37-cp37m-manylinux1_x86_64.whl (187.2 kB view details)

Uploaded CPython 3.7m

orjson-2.0.5-cp37-cp37m-macosx_10_7_x86_64.whl (176.5 kB view details)

Uploaded CPython 3.7mmacOS 10.7+ x86-64

orjson-2.0.5-cp36-none-win_amd64.whl (156.4 kB view details)

Uploaded CPython 3.6Windows x86-64

orjson-2.0.5-cp36-cp36m-manylinux1_x86_64.whl (187.2 kB view details)

Uploaded CPython 3.6m

orjson-2.0.5-cp36-cp36m-macosx_10_7_x86_64.whl (176.6 kB view details)

Uploaded CPython 3.6mmacOS 10.7+ x86-64

orjson-2.0.5-cp35-none-win_amd64.whl (156.4 kB view details)

Uploaded CPython 3.5Windows x86-64

orjson-2.0.5-cp35-cp35m-manylinux1_x86_64.whl (187.2 kB view details)

Uploaded CPython 3.5m

orjson-2.0.5-cp35-cp35m-macosx_10_7_x86_64.whl (176.6 kB view details)

Uploaded CPython 3.5mmacOS 10.7+ x86-64

File details

Details for the file orjson-2.0.5-cp37-none-win_amd64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp37-none-win_amd64.whl
  • Upload date:
  • Size: 156.4 kB
  • Tags: CPython 3.7, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.2 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.2

File hashes

Hashes for orjson-2.0.5-cp37-none-win_amd64.whl
Algorithm Hash digest
SHA256 6b2ebfb670c6fb9a32d54444cf104e92f95a4e0d8b42e4774bd391b0f790af2c
MD5 cd1fe3cb44cfdb764e84923e4071c0a4
BLAKE2b-256 b9a04a6051f2d2140797b9c2b2161dbb6b53fbb73c6b8c2d5675a57c1426020b

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp37-cp37m-manylinux1_x86_64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp37-cp37m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 187.2 kB
  • Tags: CPython 3.7m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.2 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.2

File hashes

Hashes for orjson-2.0.5-cp37-cp37m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 b5ba0cb77dcdc0f13a25064d6ad8770cfb649a170aa52aac5ec65a49e8507a51
MD5 4b283dc0aec03fa6192540b02166d881
BLAKE2b-256 4836a0bc5b1435eaa746a3ec871e31c0da5ec007bda3b30f3f4b6a9cf013bb4f

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp37-cp37m-macosx_10_7_x86_64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp37-cp37m-macosx_10_7_x86_64.whl
  • Upload date:
  • Size: 176.5 kB
  • Tags: CPython 3.7m, macOS 10.7+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.3 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.7.2

File hashes

Hashes for orjson-2.0.5-cp37-cp37m-macosx_10_7_x86_64.whl
Algorithm Hash digest
SHA256 44600616801d14a5b538116a7a6b011e7046e0f800d2558f662436e8cae2b59f
MD5 78cb840af0a1e52c59f60e5c528096a3
BLAKE2b-256 b8a4f5d1bc99c3247420247ec1fd1451051991507f8adc62acab47c691dc1f0a

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp36-none-win_amd64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp36-none-win_amd64.whl
  • Upload date:
  • Size: 156.4 kB
  • Tags: CPython 3.6, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.2 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.8

File hashes

Hashes for orjson-2.0.5-cp36-none-win_amd64.whl
Algorithm Hash digest
SHA256 2fde9d6bdcaac47e9b03562a056a93ee2b7a39f1942beee8d275db4f629c8a4d
MD5 08bff3bf2ef054d33cf08bedd67ecc2a
BLAKE2b-256 7b1965d1ebd511d35e634c16baec8573ccfe3335a7ca7cb73160dba0d9c096a4

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp36-cp36m-manylinux1_x86_64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp36-cp36m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 187.2 kB
  • Tags: CPython 3.6m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.2 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.8

File hashes

Hashes for orjson-2.0.5-cp36-cp36m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 12105e34cf7937d4dd3d2334854c3b208755922c692b7cbf527aeb4f66e0617d
MD5 cc14c24e7d317d16fece9d39e679e129
BLAKE2b-256 f7a2155ac36e773da9cda3b11712367248fd7db463dfa6e78a42bfb4a49a089d

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp36-cp36m-macosx_10_7_x86_64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp36-cp36m-macosx_10_7_x86_64.whl
  • Upload date:
  • Size: 176.6 kB
  • Tags: CPython 3.6m, macOS 10.7+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/40.6.2 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.6.8

File hashes

Hashes for orjson-2.0.5-cp36-cp36m-macosx_10_7_x86_64.whl
Algorithm Hash digest
SHA256 82b77b5167e03e8e35acb10b04bfa46d20ac312ae79418f79c032a4c0d3a92bf
MD5 be2f99acfb33e8ca40420932d1e97795
BLAKE2b-256 1d270ec151b2bc3a7874ea7ad4d1c3f40c17917544390334948dcd8b015c4d7a

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp35-none-win_amd64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp35-none-win_amd64.whl
  • Upload date:
  • Size: 156.4 kB
  • Tags: CPython 3.5, Windows x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/28.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.5.4

File hashes

Hashes for orjson-2.0.5-cp35-none-win_amd64.whl
Algorithm Hash digest
SHA256 94e55814252d20e274d6498d82bfa4886258425320ca65a105898c34bd372b87
MD5 887197a810ddd9512cc050169c8dcb0d
BLAKE2b-256 7272e082c64509f4162f7be340a364b21bd4876355c2a12b95040de2d84eca6c

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp35-cp35m-manylinux1_x86_64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp35-cp35m-manylinux1_x86_64.whl
  • Upload date:
  • Size: 187.2 kB
  • Tags: CPython 3.5m
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/28.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.5.5

File hashes

Hashes for orjson-2.0.5-cp35-cp35m-manylinux1_x86_64.whl
Algorithm Hash digest
SHA256 4b7f0c61063e1ff4b1048a5b7017762884a14fa1ba4ae3e763b3ddc5d8f1b783
MD5 a70320aa5bfbeb6acc45f3dd70b630fb
BLAKE2b-256 6989dc453b41af1d8b4eb8de97db7a6ce032cbf0728ba9083420a3692fafedb3

See more details on using hashes here.

File details

Details for the file orjson-2.0.5-cp35-cp35m-macosx_10_7_x86_64.whl.

File metadata

  • Download URL: orjson-2.0.5-cp35-cp35m-macosx_10_7_x86_64.whl
  • Upload date:
  • Size: 176.6 kB
  • Tags: CPython 3.5m, macOS 10.7+ x86-64
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/1.13.0 pkginfo/1.5.0.1 requests/2.21.0 setuptools/28.8.0 requests-toolbelt/0.9.1 tqdm/4.31.1 CPython/3.5.5

File hashes

Hashes for orjson-2.0.5-cp35-cp35m-macosx_10_7_x86_64.whl
Algorithm Hash digest
SHA256 bf7312b5ff68463fb1bc98ba5e046e4e39e864bfa177333d30c7f477b04aa355
MD5 c5f520f398f286844cdb2addd46e20a4
BLAKE2b-256 2de3256afcbe776e796249559de102357cfde2c336313b9c3c8cba5b300a7718

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page