jsonconversion Library
This Python module facilitates the conversion of arbitrary Python objects into JSON strings and back. It extends the foundational features of the native `json` package's `JSONEncoder` and `JSONDecoder` classes. Currently at version 1.2.1, it maintains an active release cadence with recent updates focusing on dependency relaxation and modernization, requiring Python 3.9 or newer.
Warnings
- breaking Version 1.0.0 introduced a significant breaking change by moving to Python 3. This means that versions prior to 1.0.0 are Python 2 compatible, while 1.0.0 and later are exclusively for Python 3.
- breaking Starting with version 1.0.2, the minimum required Python version for the library is Python 3.9. Attempting to use it with older Python 3 versions (e.g., 3.7, 3.8) will result in installation or runtime errors.
- gotcha For custom Python objects to be serializable/deserializable by `jsonconversion`, they must inherit from `jsonconversion.JSONObject` and implement both the `to_dict()` and `from_dict()` methods. Failure to do so will result in `TypeError` during encoding or decoding.
- gotcha When decoding JSON strings back into custom Python objects, `jsonconversion` relies on importing the original module path stored in the JSON. If the module containing your custom `JSONObject` subclass is not discoverable within your `PYTHONPATH` during deserialization, an `ImportError` or `ModuleNotFoundError` will occur.
Install
-
pip install jsonconversion
Imports
- JSONObject
from jsonconversion import JSONObject
- JSONObjectEncoder
from jsonconversion import JSONObjectEncoder
- JSONObjectDecoder
from jsonconversion import JSONObjectDecoder
Quickstart
import json
from jsonconversion import JSONObject, JSONObjectEncoder, JSONObjectDecoder
# 1. Define a class that inherits from JSONObject
class MyCustomObject(JSONObject):
def __init__(self, name: str, value: int):
self.name = name
self.value = value
# Required: Convert object to a dictionary for serialization
def to_dict(self) -> dict:
return {"name": self.name, "value": self.value}
# Required: Create an object from a dictionary for deserialization
@classmethod
def from_dict(cls, data: dict):
return cls(name=data["name"], value=data["value"])
def __eq__(self, other):
if not isinstance(other, MyCustomObject):
return NotImplemented
return self.name == other.name and self.value == other.value
def __repr__(self):
return f"MyCustomObject(name='{self.name}', value={self.value})"
# 2. Create an instance of your custom object
original_obj = MyCustomObject("example", 123)
print(f"Original object: {original_obj}")
# 3. Encode the object to a JSON string
# Use the JSONObjectEncoder with json.dumps
encoded_json = json.dumps(original_obj, cls=JSONObjectEncoder, indent=2)
print(f"\nEncoded JSON:\n{encoded_json}")
# 4. Decode the JSON string back to an object
# Use the JSONObjectDecoder with json.loads
decoded_obj = json.loads(encoded_json, cls=JSONObjectDecoder)
print(f"\nDecoded object: {decoded_obj}")
# 5. Verify the conversion
print(f"Objects are equal (by value): {original_obj == decoded_obj}")
print(f"Objects are identical (memory address): {original_obj is decoded_obj}")