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.1.tar.gz (6.3 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.1-py3-none-any.whl (7.3 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: extjson-0.1.1.tar.gz
  • Upload date:
  • Size: 6.3 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.1.tar.gz
Algorithm Hash digest
SHA256 4214eeaa6260dd93d14aef2b1d30577fd237b001e2409b7129a791488def4069
MD5 a0501557faeb5f88a5cf09efa2669dea
BLAKE2b-256 4e61e75efcd2cb2a36fd507f854beb94d38c762a4507d35384dd1b2c957f7544

See more details on using hashes here.

File details

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

File metadata

  • Download URL: extjson-0.1.1-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.1-py3-none-any.whl
Algorithm Hash digest
SHA256 be5370602a2ad35adf65995eea8d7f1e4d18198d5ce7e73756150dba9f559209
MD5 4eac5136a0a20d07b0d783c51a0bbf03
BLAKE2b-256 2d6611293fdbc4c94efcd1939dda12b5f60b6edaa8515236b89efbd30c5df593

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