/generic-json-encoders

More speedier and correct lilya like encoders

Primary LanguagePythonBSD 3-Clause "New" or "Revised" LicenseBSD-3-Clause

generic-json-encoders

A speedier version of the lilya encoders with more correct results and support for pydantic and msgspec. It uses under the hood orjson.

PyPI - Version PyPI - Python Version


Table of Contents

Installation

pip install generic-json-encoders

Usage

Basic

import datetime
from decimal import Decimal
from generic_json_encoders import json_encode, simplify

test_obj = {
    "datetime": datetime.datetime.now(),
    "date": datetime.date.today(),
    "decimal": Decimal("0.3").
}

# get json byte string
print(json_encode(test_obj))
# get simplified json serializable object
print(json_encode(test_obj))

Advanced

generic_json_encoders can also apply annotations in esmerald style. However the annotations must be evaluated.

import datetime
from functools import partial
from decimal import Decimal
from generic_json_encoders import apply_annotation

apply_annotation("2.333", Decimal)
apply_annotation("2.333", Decimal, partial(transform_fn=simplify))

Integrating in lilya

Put somewhere in the init code of your application

from importlib import import_module
from contextlib import suppress

...
with suppress(ImportError):
    import_module("generic_json_encoders.lilya_monkey_patcher")
...

Integrating in esmerald

import esmerald

from generic_json_encoders.lilya_monkey_patcher import GenericJsonEncoder

# you need it here too, for registering at the first place
app = esmerald.Esmerald(encoders=[GenericJsonEncoder()])

License

generic-json-encoders is distributed under the terms of the BSD license.