jsonconversion


Namejsonconversion JSON
Version 1.0.1 PyPI version JSON
download
home_page
SummaryThis python module helps converting arbitrary Python objects into JSON strings and back.
upload_time2024-03-07 16:45:58
maintainer
docs_urlNone
author
requires_python>=3.7
licenseBSD
keywords json conversion serialization
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            
The ``jsonconversion`` package
==============================

This python module helps converting arbitrary Python objects into JSON strings and back. It extends the basic features
of the ``JSONEncoder`` and ``JSONDecoder`` classes provided by the native ``json`` package. For this purpose,
``jsonconversion`` ships with these four classes:

The ``JSONObject`` class
------------------------

Your serializable classes should inherit from this class. Hereby, they must implement the methods ``from_dict`` and
``to_dict``. The example further down describes how to do so.

The ``JSONExtendedEncoder`` class
---------------------------------

This is a class used internally by ``JSONObjectEncoder``. However, it can also be used directly, if you do not need the
features of ``JSONObjectEncoder`` but want to implement your own encoders.

The class is especially helpful, if you want custom handling of builtins (``int``, ``dict``, ...) or classes deriving
from builtins. This would not be possible if directly inheriting from ``JSONEncoder``. To do so, override the
``isinstance`` method and return ``False`` for all types you want to handle in the ``default`` method.

If you look at the source code of ``JSONObjectEncoder``, you will see how this can be used.

The ``JSONObjectEncoder`` class
-------------------------------

Encodes Python objects into JSON strings. Supported objects are:

-  Python builtins: ``int``, ``float``, ``str``, ``list``, ``set``, ``dict``, ``tuple``
-  ``type`` objects: ``isinstance(object, type)``
-  All classes deriving from ``JSONObject``

Those objects can of course also be nested!

The ``JSONObjectDecoder`` class
-------------------------------

Decodes JSON strings converted using the ``JSONObjectEncoder`` back to Python objects.

The class adds a custom keyword argument to the ``load[s]`` method: ``substitute_modules``. This parameter takes a
``dict`` in the form ``{"old.module.MyClass": "new.module.MyClass"}``. It can be used if you have serialized
``JSONObject``\s who's module path has changed.

Usage
=====

Using ``jsonconversion`` is easy. You can find further code examples in the ``test`` folder.

Encoding and Decoding
---------------------

In order to encode Python objects with JSON conversion and to later decode them, you have to import the Python module
``json``. The module provides the methods ``dump``/``dumps`` for encoding and ``load``/``loads`` for decoding:

.. code:: python

    import json

    from jsonconversion.decoder import JSONObjectDecoder
    from jsonconversion.encoder import JSONObjectEncoder

    var = (1, 2, 3)  # variable to be serialized

    # "dumps" converts the variable to a string, "dump" directly writes it to a file
    str_var = json.dumps(var, cls=JSONObjectEncoder)
    # Equivalently, "loads" converts the object back from a string. "load" from a file
    var_2 = json.loads(str_var, cls=JSONObjectDecoder)
    assert var == var_2

Deriving from JSONObject
------------------------

In order to serialize arbitrary, self-written classes, they must derive from ``JSONObject`` and implement the two
methods ``from_dict`` and ``to_dict``:

.. code:: python

    class MyClass(JSONObject):

        def __init__(self, a, b, c):
            self.a = a
            self.b = b
            self.c = c

        @classmethod
        def from_dict(cls, dict_):
            return cls(dict_['a'], dict_['b'], dict_['c'])

        def to_dict(self):
            return {'a': self.a, 'b': self.b, 'c': self.c}

        def __eq__(self, other):
            return self.a == other.a and self.b == other.b and self.c == other.c

General notes
-------------

-  ``jsonconversion`` stores the class path in the JSON string when serializing a JSONObject. When decoding the object
   back, it automatically imports the correct module. You only have to ensure that the module is within your
   ``PYTHONPATH``.

-  The ``to_dict`` and ``from_dict`` methods only need to specify the elements of a class, needed to recreate the
   object. Derived attributes of a class (like ``age`` from ``year_born``) do not need to be serialized.

-  If you compare the original object with the object obtained from serialization and deserialization using ``is``, they
   will differ, as these are objects at different locations in memory. Also a comparison of JSONObject with ``==`` will
   fail, if you do not tell Python how to compare two objects. This is why ``MyClass`` overrides the ``__eq__`` method.

            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "jsonconversion",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.7",
    "maintainer_email": "",
    "keywords": "json conversion serialization",
    "author": "",
    "author_email": "Franz Steinmetz <franz.steinmetz@dlr.de>, Johannes Ernst <j.ernst@dlr.de>",
    "download_url": "https://files.pythonhosted.org/packages/88/cc/a5f1ec4c0bb2a15b9a5607926ab6c3690f88c144aa15d6b1f5b4fddc497c/jsonconversion-1.0.1.tar.gz",
    "platform": null,
    "description": "\nThe ``jsonconversion`` package\n==============================\n\nThis python module helps converting arbitrary Python objects into JSON strings and back. It extends the basic features\nof the ``JSONEncoder`` and ``JSONDecoder`` classes provided by the native ``json`` package. For this purpose,\n``jsonconversion`` ships with these four classes:\n\nThe ``JSONObject`` class\n------------------------\n\nYour serializable classes should inherit from this class. Hereby, they must implement the methods ``from_dict`` and\n``to_dict``. The example further down describes how to do so.\n\nThe ``JSONExtendedEncoder`` class\n---------------------------------\n\nThis is a class used internally by ``JSONObjectEncoder``. However, it can also be used directly, if you do not need the\nfeatures of ``JSONObjectEncoder`` but want to implement your own encoders.\n\nThe class is especially helpful, if you want custom handling of builtins (``int``, ``dict``, ...) or classes deriving\nfrom builtins. This would not be possible if directly inheriting from ``JSONEncoder``. To do so, override the\n``isinstance`` method and return ``False`` for all types you want to handle in the ``default`` method.\n\nIf you look at the source code of ``JSONObjectEncoder``, you will see how this can be used.\n\nThe ``JSONObjectEncoder`` class\n-------------------------------\n\nEncodes Python objects into JSON strings. Supported objects are:\n\n-  Python builtins: ``int``, ``float``, ``str``, ``list``, ``set``, ``dict``, ``tuple``\n-  ``type`` objects: ``isinstance(object, type)``\n-  All classes deriving from ``JSONObject``\n\nThose objects can of course also be nested!\n\nThe ``JSONObjectDecoder`` class\n-------------------------------\n\nDecodes JSON strings converted using the ``JSONObjectEncoder`` back to Python objects.\n\nThe class adds a custom keyword argument to the ``load[s]`` method: ``substitute_modules``. This parameter takes a\n``dict`` in the form ``{\"old.module.MyClass\": \"new.module.MyClass\"}``. It can be used if you have serialized\n``JSONObject``\\s who's module path has changed.\n\nUsage\n=====\n\nUsing ``jsonconversion`` is easy. You can find further code examples in the ``test`` folder.\n\nEncoding and Decoding\n---------------------\n\nIn order to encode Python objects with JSON conversion and to later decode them, you have to import the Python module\n``json``. The module provides the methods ``dump``/``dumps`` for encoding and ``load``/``loads`` for decoding:\n\n.. code:: python\n\n    import json\n\n    from jsonconversion.decoder import JSONObjectDecoder\n    from jsonconversion.encoder import JSONObjectEncoder\n\n    var = (1, 2, 3)  # variable to be serialized\n\n    # \"dumps\" converts the variable to a string, \"dump\" directly writes it to a file\n    str_var = json.dumps(var, cls=JSONObjectEncoder)\n    # Equivalently, \"loads\" converts the object back from a string. \"load\" from a file\n    var_2 = json.loads(str_var, cls=JSONObjectDecoder)\n    assert var == var_2\n\nDeriving from JSONObject\n------------------------\n\nIn order to serialize arbitrary, self-written classes, they must derive from ``JSONObject`` and implement the two\nmethods ``from_dict`` and ``to_dict``:\n\n.. code:: python\n\n    class MyClass(JSONObject):\n\n        def __init__(self, a, b, c):\n            self.a = a\n            self.b = b\n            self.c = c\n\n        @classmethod\n        def from_dict(cls, dict_):\n            return cls(dict_['a'], dict_['b'], dict_['c'])\n\n        def to_dict(self):\n            return {'a': self.a, 'b': self.b, 'c': self.c}\n\n        def __eq__(self, other):\n            return self.a == other.a and self.b == other.b and self.c == other.c\n\nGeneral notes\n-------------\n\n-  ``jsonconversion`` stores the class path in the JSON string when serializing a JSONObject. When decoding the object\n   back, it automatically imports the correct module. You only have to ensure that the module is within your\n   ``PYTHONPATH``.\n\n-  The ``to_dict`` and ``from_dict`` methods only need to specify the elements of a class, needed to recreate the\n   object. Derived attributes of a class (like ``age`` from ``year_born``) do not need to be serialized.\n\n-  If you compare the original object with the object obtained from serialization and deserialization using ``is``, they\n   will differ, as these are objects at different locations in memory. Also a comparison of JSONObject with ``==`` will\n   fail, if you do not tell Python how to compare two objects. This is why ``MyClass`` overrides the ``__eq__`` method.\n",
    "bugtrack_url": null,
    "license": "BSD",
    "summary": "This python module helps converting arbitrary Python objects into JSON strings and back.",
    "version": "1.0.1",
    "project_urls": {
        "Homepage": "https://github.com/DLR-RM/python-jsonconversion"
    },
    "split_keywords": [
        "json",
        "conversion",
        "serialization"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "15a08500d44765cc54caa5232b6eb8864be936628d711d51c92bdd360c77833d",
                "md5": "ad2f3566623627bcd5dcebd74222c0f9",
                "sha256": "81282f94df8489ed74d1e67d5b128a4c9de64067b88ea8c49359c278b36178f5"
            },
            "downloads": -1,
            "filename": "jsonconversion-1.0.1-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "ad2f3566623627bcd5dcebd74222c0f9",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.7",
            "size": 11053,
            "upload_time": "2024-03-07T16:45:57",
            "upload_time_iso_8601": "2024-03-07T16:45:57.409991Z",
            "url": "https://files.pythonhosted.org/packages/15/a0/8500d44765cc54caa5232b6eb8864be936628d711d51c92bdd360c77833d/jsonconversion-1.0.1-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "88cca5f1ec4c0bb2a15b9a5607926ab6c3690f88c144aa15d6b1f5b4fddc497c",
                "md5": "0fd6ce4d8f4f444c44d982443572f511",
                "sha256": "1bfaa72a471dba0a9254abba9daa8d2b30e9327b8e012992732adae2bc1df3ce"
            },
            "downloads": -1,
            "filename": "jsonconversion-1.0.1.tar.gz",
            "has_sig": false,
            "md5_digest": "0fd6ce4d8f4f444c44d982443572f511",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.7",
            "size": 9418,
            "upload_time": "2024-03-07T16:45:58",
            "upload_time_iso_8601": "2024-03-07T16:45:58.751833Z",
            "url": "https://files.pythonhosted.org/packages/88/cc/a5f1ec4c0bb2a15b9a5607926ab6c3690f88c144aa15d6b1f5b4fddc497c/jsonconversion-1.0.1.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-03-07 16:45:58",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "DLR-RM",
    "github_project": "python-jsonconversion",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "tox": true,
    "lcname": "jsonconversion"
}
        
Elapsed time: 0.21038s