Skip to main content

Utility library for serializing/deserializing custom Python objects to/from JSON.

Project description

from pyobjson import PythonObjectJson

pyobjson - Python Object JSON Tool

Utility library for serializing/deserializing custom Python objects to/from JSON.

GitHub release (latest SemVer) GitHub tag (latest SemVer) GitHub Workflow Status (with event)

PyPI PyPI PyPI PyPI


Do you like the Python Object JSON Tool? Star the repository on GitHub and please consider helping support its ongoing development:


READ THE DOCS HERE!
Detailed documentation can be found at https://pyobjson.wrencode.dev.

 

Table of Contents


About

The Python Object JSON Tool is a utility library for serializing/deserializing custom Python objects to/from JSON by using pyobjson classes as superclasses/parent classes to your custom Python classes.

Installation

You can install with pip by running:

pip install pyobjson

Note: If you wish to use pyobjson to serialize/deserialize custom Python objects to/from MongoDB, then you have to install with the optional dependencies:

pip install pyobjson[mongo]

Dependencies

The base Python Object JSON Tool does not have any third-party dependencies to run the code. It has several development dependencies, which can be seen in the package pyproject.toml.

If you wish to use pyobjson to serialize/deserialize custom Python objects to/from MongoDB, then there is an additional dependency on the PyMongo package.

Toolchain

The below tools and resources are used as part of pyobjson:

  • uv - package management
  • ruff - code linting
  • bandit - code security
  • make - Makefile build automation
  • MkDocs - package documentation
  • python-dotenv - programmatic access to environment variables defined in a .env file
  • pytest - code testing framework
  • GitHub Actions - CI/CD
  • act - GitHub Actions testing

Usage

The pyobjson package is designed to be used as a base class/parent class/superclass to your own custom Python classes in order to provide built-in, convenient serialization/deserialization functionality. Child classes/subclasses of pyobjson.base.PythonObjectJson will automatically have the following methods:

  • pyobjson.base.PythonObjectJson.serialize(): Create a serializable dictionary from the class instance.
  • pyobjson.base.PythonObjectJson.to_json_str(): Serialize the class instance to a JSON string.
  • pyobjson.base.PythonObjectJson.from_json_str(json_str): Load the class instance from a pyobjson-formatted JSON string.
  • pyobjson.base.PythonObjectJson.save_to_json_file(json_file_path): Save the class instance to a JSON file.
  • pyobjson.base.PythonObjectJson.load_from_json_file(json_file_path): Load the class instance from a pyobjson-formatted JSON file.

Please reference the documentation at https://pyobjson.wrencode.dev for more detailed usage.

JSON Example

from pyobjson.base import PythonObjectJson

class MyOtherClass(PythonObjectJson):
    
    def __init__(self):
        super().__init__()
        self.message = "Hello, World!"

class MyClass(PythonObjectJson):
    def __init__(self):
        super().__init__()
        self.my_other_classes = [MyOtherClass()]

my_class = MyClass()

print(my_class.to_json_str())

JSON Example Output
{
  "__main__.myclass": {
    "collection:list.my_other_classes": [
      {
        "__main__.myotherclass": {
          "message": "Hello, World!"
        }
      }
    ]
  }
}

The above example shows how pyobjson can be used to serialize arbitrary custom Python classes into JSON. Additionally, the above JSON example output JSON can be used to recreate an equivalent class instance by loading the JSON into a custom Python class instance.

Saving and Loading

The pyobjson.base.PythonObjectJson parent class also provides built-in methods to save/load arbitrary custom Python classes to/from JSON in several ways.

JSON Files
  • JSON files (using only Python built-in libraries): Use the PythonObjectJson.save_to_json_file(json_file_path) and PythonObjectJson.load_from_json_file(json_file_path) methods to save/load your custom Python subclasses to JSON files.

JSON File Example
from pathlib import Path

from dotenv import load_dotenv

from pyobjson.base import PythonObjectJson

root_dir = Path(__file__).parent

load_dotenv(root_dir / ".env")


class CustomClassToJsonFile(PythonObjectJson):
    def __init__(self, message: str):
        super().__init__()
        self.message = message


custom_class_to_json_file = CustomClassToJsonFile("Hello, World!")

output_dir = root_dir / "output"
if not output_dir.is_dir():
    output_dir.mkdir(parents=True, exist_ok=True)

custom_class_to_json_file.save_to_json_file(output_dir / "custom_class_to_json_file.json")

custom_class_to_json_file.load_from_json_file(output_dir / "custom_class_to_json_file.json")

JSON File Output
{
  "__main__.customclasstojsonfile": {
    "message": "Hello, World!"
  }
}

MongoDB
  • MongoDB (using pymongo): The pyobjson library includes a class called pyobjson.dao.PythonObjectJsonToMongo, which can be used as a superclass for any custom class you wish to be able to easily serialized/deserialize to/from MongoDB. Use the PythonObjectJsonToMongo.save_to_mongo(mongo_collection) and PythonObjectJsonToMongo.load_from_mongo(mongo_collection, document_id) methods to save/load your custom Python subclasses to MongoDB.

MongoDB Example
import os
from pathlib import Path

from dotenv import load_dotenv

from pyobjson.dao.mongo.base import PythonObjectJsonToMongo

load_dotenv(Path(__file__).parent / ".env")


class CustomClassToMongo(PythonObjectJsonToMongo):
    def __init__(self, mongo_host: str, mongo_port: int, mongo_database: str, mongo_user: str, mongo_password: str):
        super().__init__(mongo_host, mongo_port, mongo_database, mongo_user, mongo_password)
        self.message = "Hello, World!"


custom_class_to_mongo = CustomClassToMongo(
    mongo_host=os.environ.get("MONGO_HOST"),
    mongo_port=int(os.environ.get("MONGO_PORT")),
    mongo_database=os.environ.get("MONGO_DATABASE"),
    mongo_user=os.environ.get("MONGO_ADMIN_USER"),
    mongo_password=os.environ.get("MONGO_ADMIN_PASS"),
)

saved_mongo_document_id = custom_class_to_mongo.save_to_mongo(os.environ.get("MONGO_COLLECTION"))

custom_class_to_mongo.load_from_mongo(os.environ.get("MONGO_COLLECTION"), saved_mongo_document_id)

MongoDB Output

print(custom_class_to_mongo):

{
  "__main__.customclasstomongo": {
    "message": "Hello, World!"
  }
}

print(repr(custom_class_to_mongo)):

__main__.CustomClassToMongo(mongo_host=localhost,mongo_port=27017,mongo_database=pyobjson,mongo_user=<mongodb_user>,mongo_password=<mongodb_password>)

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

pyobjson-5.1.1.tar.gz (3.1 MB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pyobjson-5.1.1-py3-none-any.whl (14.9 kB view details)

Uploaded Python 3

File details

Details for the file pyobjson-5.1.1.tar.gz.

File metadata

  • Download URL: pyobjson-5.1.1.tar.gz
  • Upload date:
  • Size: 3.1 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.5.8

File hashes

Hashes for pyobjson-5.1.1.tar.gz
Algorithm Hash digest
SHA256 ac8c9b2b886e23a21491310ccca8277f29d22e81f93f6c0b2e5148855ed1db7f
MD5 b77accc055cc6d63e9723ddb5abab843
BLAKE2b-256 4c4bfd81d480034a1428f177ba39540ec53de1957db41b3eac78225bb2d86d05

See more details on using hashes here.

File details

Details for the file pyobjson-5.1.1-py3-none-any.whl.

File metadata

  • Download URL: pyobjson-5.1.1-py3-none-any.whl
  • Upload date:
  • Size: 14.9 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: uv/0.5.8

File hashes

Hashes for pyobjson-5.1.1-py3-none-any.whl
Algorithm Hash digest
SHA256 f36e35a3605808df7d5d20cf5ae0ece0e654f7943bb8d8fa87b753f76d3be4d2
MD5 55918c22cd07e48984ea9a327b76b2fb
BLAKE2b-256 f6ebebbab6b95d0e729aaea3f56f1bd6d976239e0a82272232d32e2fe067f897

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page