JSON Handler Registry
Standardized way of registering custom JSON serializers/deserializers.
Package json lacks standard approach to registering custom JSON handlers.
Project json-handler-registry has been created to solve that issue.
Usage:
Registering your own handlers:
from typing import Optional
from json_handler_registry.registry import JsonHandlerRegistry
from json_handler_registry.encoder import IJsonEncoder, EncodingResult
from json_handler_registry.decoder import IJsonDecoder
# Implement your custom class encoder:
class MyJsonEncoder(IJsonEncoder):
def encodeObject(self, obj: object) -> Optional[EncodingResult]:
"""Convert object to a JSON serializable data.
Or return ``None`` instead.
"""
pass # TODO: Actual implementation goes here!
# Implement your custom class decoder:
class MyJsonDecoder(IJsonDecoder):
def decodeDict(self, dct: dict) -> Optional[object]:
"""Convert dictionary to your type instance.
Or return ``None`` instead.
"""
pass # TODO: Actual implementation goes here!
def decodeStr(self, valueStr: str) -> Optional[object]:
"""Convert string value to your type instance.
Or return ``None`` instead.
"""
pass # TODO: Actual implementation goes here!
# Register your serializer and deserializer:
JsonHandlerRegistry.registerEncoder(MyJsonEncoder())
JsonHandlerRegistry.registerDecoder(MyJsonDecoder())
Serialization & deserialization:
# Using `tunit` package as an example:
import json
from tunit.config import TUnitConfig
from tunit.unit import Seconds
TUnitConfig.registerJsonHandler() # Enables registry and registers handlers.
# JSON serialization:
messageDto = {"delay": Seconds(10)}
messageJson = json.dumps(messageDto)
print(messageJson) # Prints: '{"delay": "10s"}'
# JSON deserialization:
messageJson = '{"delay": "10s"}'
messageDto = json.loads(messageJson)
print(messageDto) # Prints: {'delay': Seconds(10)}
Popular external packages support:
Package maintainers are encouraged to adopt json-handler-registry in their projects.
However, for now, support for popular packages will be successively provided here.
Support for dataclasses-json:
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from enum import Enum, auto
from uuid import UUID, uuid4
from dataclasses_json import DataClassJsonMixin
from json_handler_registry.registry import JsonHandlerRegistry
class TestEnum(Enum):
Option1 = auto()
Option2 = auto()
Option3 = auto()
@dataclass
class TestDataClass(DataClassJsonMixin):
timestamp: datetime
id: UUID
option: TestEnum
value: Decimal
testData = TestDataClass(
timestamp=datetime.now().astimezone(),
id=uuid4(),
option=TestEnum.Option2,
value=Decimal(7)
)
JsonHandlerRegistry.packageSupportManager.getPackageSupportConfig('dataclasses-json').enable()
assert TestDataClass.from_json(testData.to_json()) == testData
JsonHandlerRegistry.packageSupportManager.getPackageSupportConfig('dataclasses-json').disable()
# Instead of using 'PackageSupportManager' you can also manually register encoder:
from json_handler_registry.registry import JsonHandlerRegistry
from json_handler_registry.support.impl.dataclasses_json import DataClassJsonEncoder
JsonHandlerRegistry.registerEncoder(DataClassJsonEncoder)
Changelog:
- Version: 1.5.0
- Package support manager is now accessible from handler registry.
- Version: 1.4.0
- Preserving registration order of encoders/decoders.
- Configurable auto enable/disable registry feature. (Active by default.)
- Version: 1.3.0
- Support for
dataclasses-jsonpackage. - Debug methods for listing registered encoders/decoders.
- Support for
- Version: 1.2.0
- Guard to prevent registry from being easily overridden when enabled.
- Version: 1.1.0
- Registry accepts both type and instance of encoder/decoder.
License
MIT
Metadata
Release files for json-handler-registry 1.5.1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | |
|---|---|---|---|---|
| json-handler-registry-1.5.1.tar.gz | 6.4 kB | Without provenance | Details |
Release files / json-handler-registry-1.5.1.tar.gz
| Download URL | json-handler-registry-1.5.1.tar.gz |
|---|---|
| Size | 6.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
3351f2745b70eaecbb53ccf634a50bebf74329b3b8781caa341988476c24d57e
|
|
BLAKE2b-256 checksum How to use checksums |
32afadb493fc649e9d214e818be2011a495dd328cd634f4c7110a58e95211195
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/4.0.2 CPython/3.7.16
|
Security for json-handler-registry 1.5.1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.