Skip to main content

Extended JSON serialization library supporting main BSON types (datetime, bytes, UUID, Decimal, …)

Project description

extjson

The extjson library is a small Python module for serializing and deserializing data to/from JSON, following MongoDB Extended JSON conventions.

It currently adds support for these common types:

  • datetime.datetime (timezone-aware)
  • bytes
  • uuid.UUID
  • decimal.Decimal
  • special floating-point values (NaN, Infinity, -Infinity)

For naive datetimes, or for separate dates/times, use JSON strings with your own formatting (e.g. isoformat()).

Serialization can be done in two modes:

  • Relaxed mode (default): use native JSON numbers, iso-formatted dates, and simple $uuid wrappers, wherever possible.
  • Canonical mode: use strict Extended JSON wrappers such as $numberInt, $numberLong, $numberDouble, $binary... for every value. Much less readable, but more straightforward to parse.

Note that the parser will transparently decode both formats.

For the complete Extended JSON specification, see https://www.mongodb.com/docs/languages/python/pymongo-driver/current/data-formats/extended-json/

Installation

Install from PyPI:

pip install extjson

Quick start

from datetime import datetime, timezone
from decimal import Decimal
import uuid

from extjson import convert_from_extjson, convert_to_extjson

payload = {
    "id": uuid.UUID("f47ac10b-58cc-4372-a567-0e02b2c3d479"),
    "created_at": datetime(2024, 1, 16, 12, 30, tzinfo=timezone.utc),
    "price": Decimal("19.99"),
    "raw": b"hello",
}

ext_doc = convert_to_extjson(payload, canonical=True)
roundtrip = convert_from_extjson(ext_doc)

assert roundtrip == payload

Canonical vs relaxed mode

Use convert_to_extjson(..., canonical=True|False):

from extjson import convert_to_extjson

print(convert_to_extjson(42, canonical=True))   # {'$numberInt': '42'}
print(convert_to_extjson(42, canonical=False))  # 42

High-level JSON helpers

If you want JSON strings/bytes/files directly, use the helper API:

  • dumps(obj, **json_kwargs) / loads(data, **json_kwargs): replacements for stdlib JSON functions
  • dump_to_json_str(data, **json_kwargs) / load_from_json_str(data, **json_kwargs): same as above, but preconfigured for reproducibility (e.g. sort_keys=True)
  • dump_to_json_bytes(data, **json_kwargs) / load_from_json_bytes(data, **json_kwargs)
  • dump_to_json_file(path, data, **json_kwargs) / load_from_json_file(path, **json_kwargs)

All these functions accept a canonical=True|False argument, and forward the rest to the underlying json functions (e.g. indent=2 for pretty-printing).

import uuid
from extjson import dump_to_json_str, load_from_json_str

payload = {"name": "hello", "blob": b"xyz", "uid": uuid.uuid4()}

json_text = dump_to_json_str(payload)
back = load_from_json_str(json_text)

assert back == payload

Notes and behavior details

  • When encoding, datetimes must be timezone-aware.
  • When encoding, tuples and their content remain untouched (only lists and dicts are recursively processed).
  • Decoded datetimes are normalized to UTC timezone.
  • NaN values round-trip, but NaN != NaN still applies in Python comparisons.

License

MIT

Project details


Download files

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

Source Distribution

extjson-0.1.0.tar.gz (6.2 kB view details)

Uploaded Source

Built Distribution

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

extjson-0.1.0-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

Details for the file extjson-0.1.0.tar.gz.

File metadata

  • Download URL: extjson-0.1.0.tar.gz
  • Upload date:
  • Size: 6.2 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.13.2 Windows/11

File hashes

Hashes for extjson-0.1.0.tar.gz
Algorithm Hash digest
SHA256 18d7c4fa5a6b7c2ff3dd40cabd552fa9c4c7657bc40e21effd3cfa8ddd874d92
MD5 512d879ac004449790da569a34027c8a
BLAKE2b-256 4ccefa52a6a466642ed0a513a61b404607a2b149234d780beb0973df65be1dff

See more details on using hashes here.

File details

Details for the file extjson-0.1.0-py3-none-any.whl.

File metadata

  • Download URL: extjson-0.1.0-py3-none-any.whl
  • Upload date:
  • Size: 7.3 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.13.2 Windows/11

File hashes

Hashes for extjson-0.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 2909bb36880bbf7b53bcbe15202375031aa4b4819401f041e2cc719468ee8286
MD5 fa657a022061ad570fa10c7b407c6317
BLAKE2b-256 d1cac08fa8b5eaf08d9e040a6baa167e3ac29e0d7cf1b82bf3121fff861b930b

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