Standardized way of registering custom JSON serializers/deserializers.
Project description
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
# Enable registry:
JsonHandlerRegistry.enable()
# 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)}
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
Close
Hashes for json-handler-registry-1.1.0.tar.gz
Algorithm | Hash digest | |
---|---|---|
SHA256 | 502e8e075ed0c52f49040b01523743196df480dcf27f38fd3a59a1aae7fea976 |
|
MD5 | 94cffd01006ac0f143ce3e3d908e8068 |
|
BLAKE2b-256 | 5ab383f91986278134cffa4c81d8dfafd3df3806bd62ede28b041f5124a1c57a |