jsonconversion Library

1.2.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to define a custom class inheriting from `JSONObject`, implement the required `to_dict` and `from_dict` methods, and then use `JSONObjectEncoder` and `JSONObjectDecoder` with the standard `json` module to serialize and deserialize instances of your custom class.

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}")

view raw JSON →