[![PyPI pyversions](https://img.shields.io/pypi/pyversions/json-handler-registry.svg)](https://pypi.python.org/pypi/json-handler-registry)
[![PyPI version shields.io](https://img.shields.io/pypi/v/json-handler-registry.svg)](https://pypi.python.org/pypi/json-handler-registry)
[![PyPI license](https://img.shields.io/pypi/l/json-handler-registry.svg)](https://pypi.python.org/pypi/json-handler-registry)
[![Downloads](https://static.pepy.tech/badge/json-handler-registry)](https://pepy.tech/project/json-handler-registry)
# 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:
```python
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:
```python
# 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`:
```python
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-json` package.
- Debug methods for listing registered encoders/decoders.
- 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
Raw data
{
"_id": null,
"home_page": null,
"name": "json-handler-registry",
"maintainer": null,
"docs_url": null,
"requires_python": ">=3.7",
"maintainer_email": null,
"keywords": "json, serialization, deserialization",
"author": null,
"author_email": "\"P.J. Grochowski\" <pawel.grochowski.dev@gmail.com>",
"download_url": "https://files.pythonhosted.org/packages/32/af/adb493fc649e9d214e818be2011a495dd328cd634f4c7110a58e95211195/json-handler-registry-1.5.1.tar.gz",
"platform": null,
"description": "[![PyPI pyversions](https://img.shields.io/pypi/pyversions/json-handler-registry.svg)](https://pypi.python.org/pypi/json-handler-registry)\n[![PyPI version shields.io](https://img.shields.io/pypi/v/json-handler-registry.svg)](https://pypi.python.org/pypi/json-handler-registry)\n[![PyPI license](https://img.shields.io/pypi/l/json-handler-registry.svg)](https://pypi.python.org/pypi/json-handler-registry)\n[![Downloads](https://static.pepy.tech/badge/json-handler-registry)](https://pepy.tech/project/json-handler-registry)\n\n# JSON Handler Registry\n---\nStandardized way of registering custom JSON serializers/deserializers.\n\nPackage `json` lacks standard approach to registering custom JSON handlers.\n\nProject `json-handler-registry` has been created to solve that issue.\n\n## Usage:\n\nRegistering your own handlers:\n\n```python\nfrom typing import Optional\nfrom json_handler_registry.registry import JsonHandlerRegistry\nfrom json_handler_registry.encoder import IJsonEncoder, EncodingResult\nfrom json_handler_registry.decoder import IJsonDecoder\n\n\n# Implement your custom class encoder:\nclass MyJsonEncoder(IJsonEncoder):\n def encodeObject(self, obj: object) -> Optional[EncodingResult]:\n \"\"\"Convert object to a JSON serializable data.\n Or return ``None`` instead.\n \"\"\"\n pass # TODO: Actual implementation goes here!\n\n\n# Implement your custom class decoder:\nclass MyJsonDecoder(IJsonDecoder):\n def decodeDict(self, dct: dict) -> Optional[object]:\n \"\"\"Convert dictionary to your type instance.\n Or return ``None`` instead.\n \"\"\"\n pass # TODO: Actual implementation goes here!\n\n def decodeStr(self, valueStr: str) -> Optional[object]:\n \"\"\"Convert string value to your type instance.\n Or return ``None`` instead.\n \"\"\"\n pass # TODO: Actual implementation goes here!\n\n\n# Register your serializer and deserializer:\nJsonHandlerRegistry.registerEncoder(MyJsonEncoder())\nJsonHandlerRegistry.registerDecoder(MyJsonDecoder())\n```\n\nSerialization & deserialization:\n```python\n# Using `tunit` package as an example:\nimport json\nfrom tunit.config import TUnitConfig\nfrom tunit.unit import Seconds\n\nTUnitConfig.registerJsonHandler() # Enables registry and registers handlers.\n\n# JSON serialization:\nmessageDto = {\"delay\": Seconds(10)}\nmessageJson = json.dumps(messageDto)\nprint(messageJson) # Prints: '{\"delay\": \"10s\"}'\n\n# JSON deserialization:\nmessageJson = '{\"delay\": \"10s\"}'\nmessageDto = json.loads(messageJson)\nprint(messageDto) # Prints: {'delay': Seconds(10)}\n```\n\n## Popular external packages support:\n\nPackage maintainers are encouraged to adopt `json-handler-registry` in their projects.\nHowever, for now, support for popular packages will be successively provided here.\n\nSupport for `dataclasses-json`:\n\n```python\nfrom dataclasses import dataclass\nfrom datetime import datetime\nfrom decimal import Decimal\nfrom enum import Enum, auto\nfrom uuid import UUID, uuid4\n\nfrom dataclasses_json import DataClassJsonMixin\nfrom json_handler_registry.registry import JsonHandlerRegistry\n\n\nclass TestEnum(Enum):\n Option1 = auto()\n Option2 = auto()\n Option3 = auto()\n\n\n@dataclass\nclass TestDataClass(DataClassJsonMixin):\n timestamp: datetime\n id: UUID\n option: TestEnum\n value: Decimal\n\n\ntestData = TestDataClass(\n timestamp=datetime.now().astimezone(),\n id=uuid4(),\n option=TestEnum.Option2,\n value=Decimal(7)\n)\n\nJsonHandlerRegistry.packageSupportManager.getPackageSupportConfig('dataclasses-json').enable()\nassert TestDataClass.from_json(testData.to_json()) == testData\nJsonHandlerRegistry.packageSupportManager.getPackageSupportConfig('dataclasses-json').disable()\n\n# Instead of using 'PackageSupportManager' you can also manually register encoder:\nfrom json_handler_registry.registry import JsonHandlerRegistry\nfrom json_handler_registry.support.impl.dataclasses_json import DataClassJsonEncoder\nJsonHandlerRegistry.registerEncoder(DataClassJsonEncoder)\n```\n\n### Changelog:\n---\n- Version: 1.5.0\n - Package support manager is now accessible from handler registry.\n- Version: 1.4.0\n - Preserving registration order of encoders/decoders.\n - Configurable auto enable/disable registry feature. (Active by default.)\n- Version: 1.3.0\n - Support for `dataclasses-json` package.\n - Debug methods for listing registered encoders/decoders.\n- Version: 1.2.0\n - Guard to prevent registry from being easily overridden when enabled.\n- Version: 1.1.0\n - Registry accepts both type and instance of encoder/decoder.\n\n## License\nMIT\n",
"bugtrack_url": null,
"license": "MIT",
"summary": "Standardized way of registering custom JSON serializers/deserializers.",
"version": "1.5.1",
"project_urls": {
"Repository": "https://bitbucket.org/massultidev/json-handler-registry"
},
"split_keywords": [
"json",
" serialization",
" deserialization"
],
"urls": [
{
"comment_text": "",
"digests": {
"blake2b_256": "32afadb493fc649e9d214e818be2011a495dd328cd634f4c7110a58e95211195",
"md5": "8820739ce78e7424caf92f33e07faa9a",
"sha256": "3351f2745b70eaecbb53ccf634a50bebf74329b3b8781caa341988476c24d57e"
},
"downloads": -1,
"filename": "json-handler-registry-1.5.1.tar.gz",
"has_sig": false,
"md5_digest": "8820739ce78e7424caf92f33e07faa9a",
"packagetype": "sdist",
"python_version": "source",
"requires_python": ">=3.7",
"size": 6413,
"upload_time": "2024-04-07T16:56:56",
"upload_time_iso_8601": "2024-04-07T16:56:56.796233Z",
"url": "https://files.pythonhosted.org/packages/32/af/adb493fc649e9d214e818be2011a495dd328cd634f4c7110a58e95211195/json-handler-registry-1.5.1.tar.gz",
"yanked": false,
"yanked_reason": null
}
],
"upload_time": "2024-04-07 16:56:56",
"github": false,
"gitlab": false,
"bitbucket": true,
"codeberg": false,
"bitbucket_user": "massultidev",
"bitbucket_project": "json-handler-registry",
"lcname": "json-handler-registry"
}