znjson


Nameznjson JSON
Version 0.2.2 PyPI version JSON
download
home_page
SummaryA Python Package to Encode/Decode some common file formats to json
upload_time2023-03-10 10:51:04
maintainer
docs_urlNone
authorzincwarecode
requires_python>=3.8,<4.0
licenseApache-2.0
keywords json zntrack jsonpickle serialization deserialization
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            [![Coverage Status](https://coveralls.io/repos/github/zincware/ZnJSON/badge.svg?branch=main)](https://coveralls.io/github/zincware/ZnJSON?branch=main)
[![Code Style](https://img.shields.io/badge/code%20style-black-black)](https://github.com/psf/black/)
[![Tests](https://github.com/zincware/ZnJSON/actions/workflows/pytest.yaml/badge.svg)](https://coveralls.io/github/zincware/ZnJSON?branch=main)
[![PyPI version](https://badge.fury.io/py/znjson.svg)](https://badge.fury.io/py/znjson)


# ZnJSON

Package to Encode/Decode some common file formats to json

Available via ``pip install znjson``

In comparison to `pickle` this allows having readable json files combined with some
serialized data.

# Example

````python
import numpy as np
import json
import znjson

data = json.dumps(
    obj={"data_np": np.arange(2), "data": [x for x in range(10)]},
    cls=znjson.ZnEncoder,
    indent=4
)
_ = json.loads(data, cls=znjson.ZnDecoder)
````
The resulting ``*.json`` file is partially readable and looks like this:

````json
{
    "data_np": {
        "_type": "np.ndarray_small",
        "value": [
            0,
            1
        ]
    },
    "data": [
        0,
        1,
        2,
        3,
        4
    ]
}
````

# Custom Converter

ZnJSON allows you to easily add custom converters.
Let's write a serializer for ``datetime.datetime``. 

````python
from znjson import ConverterBase
from datetime import datetime

class DatetimeConverter(ConverterBase):
    """Encode/Decode datetime objects

    Attributes
    ----------
    level: int
        Priority of this converter over others.
        A higher level will be used first, if there
        are multiple converters available
    representation: str
        An unique identifier for this converter.
    instance:
        Used to select the correct converter.
        This should fulfill isinstance(other, self.instance)
        or __eq__ should be overwritten.
    """
    level = 100
    representation = "datetime"
    instance = datetime

    def encode(self, obj: datetime) -> str:
        """Convert the datetime object to str / isoformat"""
        return obj.isoformat()
    def decode(self, value: str) -> datetime:
        """Create datetime object from str / isoformat"""
        return datetime.fromisoformat(value)
````

This allows us to use this new serializer:
````python
znjson.config.register(DatetimeConverter) # we need to register the new converter first
json_string = json.dumps(dt, cls=znjson.ZnEncoder, indent=4)
json.loads(json_string, cls=znjson.ZnDecoder)
````

and will result in
````json
{
    "_type": "datetime",
    "value": "2022-03-11T09:47:35.280331"
}
````

If you don't want to register your converter to be used everywhere, simply use:

```python
json_string = json.dumps(dt, cls=znjson.ZnEncoder.from_converters(DatetimeConverter))
```
            

Raw data

            {
    "_id": null,
    "home_page": "",
    "name": "znjson",
    "maintainer": "",
    "docs_url": null,
    "requires_python": ">=3.8,<4.0",
    "maintainer_email": "",
    "keywords": "json,zntrack,jsonpickle,serialization,deserialization",
    "author": "zincwarecode",
    "author_email": "zincwarecode@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/4d/20/377ca1283b9288b7bf816966d19af2bd996195ac4f1a46fbdcc82aa9224b/znjson-0.2.2.tar.gz",
    "platform": null,
    "description": "[![Coverage Status](https://coveralls.io/repos/github/zincware/ZnJSON/badge.svg?branch=main)](https://coveralls.io/github/zincware/ZnJSON?branch=main)\n[![Code Style](https://img.shields.io/badge/code%20style-black-black)](https://github.com/psf/black/)\n[![Tests](https://github.com/zincware/ZnJSON/actions/workflows/pytest.yaml/badge.svg)](https://coveralls.io/github/zincware/ZnJSON?branch=main)\n[![PyPI version](https://badge.fury.io/py/znjson.svg)](https://badge.fury.io/py/znjson)\n\n\n# ZnJSON\n\nPackage to Encode/Decode some common file formats to json\n\nAvailable via ``pip install znjson``\n\nIn comparison to `pickle` this allows having readable json files combined with some\nserialized data.\n\n# Example\n\n````python\nimport numpy as np\nimport json\nimport znjson\n\ndata = json.dumps(\n    obj={\"data_np\": np.arange(2), \"data\": [x for x in range(10)]},\n    cls=znjson.ZnEncoder,\n    indent=4\n)\n_ = json.loads(data, cls=znjson.ZnDecoder)\n````\nThe resulting ``*.json`` file is partially readable and looks like this:\n\n````json\n{\n    \"data_np\": {\n        \"_type\": \"np.ndarray_small\",\n        \"value\": [\n            0,\n            1\n        ]\n    },\n    \"data\": [\n        0,\n        1,\n        2,\n        3,\n        4\n    ]\n}\n````\n\n# Custom Converter\n\nZnJSON allows you to easily add custom converters.\nLet's write a serializer for ``datetime.datetime``. \n\n````python\nfrom znjson import ConverterBase\nfrom datetime import datetime\n\nclass DatetimeConverter(ConverterBase):\n    \"\"\"Encode/Decode datetime objects\n\n    Attributes\n    ----------\n    level: int\n        Priority of this converter over others.\n        A higher level will be used first, if there\n        are multiple converters available\n    representation: str\n        An unique identifier for this converter.\n    instance:\n        Used to select the correct converter.\n        This should fulfill isinstance(other, self.instance)\n        or __eq__ should be overwritten.\n    \"\"\"\n    level = 100\n    representation = \"datetime\"\n    instance = datetime\n\n    def encode(self, obj: datetime) -> str:\n        \"\"\"Convert the datetime object to str / isoformat\"\"\"\n        return obj.isoformat()\n    def decode(self, value: str) -> datetime:\n        \"\"\"Create datetime object from str / isoformat\"\"\"\n        return datetime.fromisoformat(value)\n````\n\nThis allows us to use this new serializer:\n````python\nznjson.config.register(DatetimeConverter) # we need to register the new converter first\njson_string = json.dumps(dt, cls=znjson.ZnEncoder, indent=4)\njson.loads(json_string, cls=znjson.ZnDecoder)\n````\n\nand will result in\n````json\n{\n    \"_type\": \"datetime\",\n    \"value\": \"2022-03-11T09:47:35.280331\"\n}\n````\n\nIf you don't want to register your converter to be used everywhere, simply use:\n\n```python\njson_string = json.dumps(dt, cls=znjson.ZnEncoder.from_converters(DatetimeConverter))\n```",
    "bugtrack_url": null,
    "license": "Apache-2.0",
    "summary": "A Python Package to Encode/Decode some common file formats to json",
    "version": "0.2.2",
    "split_keywords": [
        "json",
        "zntrack",
        "jsonpickle",
        "serialization",
        "deserialization"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "558f2ec0d72be2682e43c18dcecc33f578a005b5f0076d6c2186223e400ec307",
                "md5": "da1df22071660af9abb89b2434ab2bf1",
                "sha256": "ee29bb63716f66d1d259a8e3565fb66b9c8b79aee896dc231df990ad26e7fb6b"
            },
            "downloads": -1,
            "filename": "znjson-0.2.2-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "da1df22071660af9abb89b2434ab2bf1",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.8,<4.0",
            "size": 14598,
            "upload_time": "2023-03-10T10:50:59",
            "upload_time_iso_8601": "2023-03-10T10:50:59.086130Z",
            "url": "https://files.pythonhosted.org/packages/55/8f/2ec0d72be2682e43c18dcecc33f578a005b5f0076d6c2186223e400ec307/znjson-0.2.2-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "4d20377ca1283b9288b7bf816966d19af2bd996195ac4f1a46fbdcc82aa9224b",
                "md5": "bbc9d45be62754ac62cf5a34763c7d0d",
                "sha256": "d421ff377d490d876ea016780ffd60a585949a29d6df28ae971da2a329f35b45"
            },
            "downloads": -1,
            "filename": "znjson-0.2.2.tar.gz",
            "has_sig": false,
            "md5_digest": "bbc9d45be62754ac62cf5a34763c7d0d",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.8,<4.0",
            "size": 12255,
            "upload_time": "2023-03-10T10:51:04",
            "upload_time_iso_8601": "2023-03-10T10:51:04.425846Z",
            "url": "https://files.pythonhosted.org/packages/4d/20/377ca1283b9288b7bf816966d19af2bd996195ac4f1a46fbdcc82aa9224b/znjson-0.2.2.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2023-03-10 10:51:04",
    "github": false,
    "gitlab": false,
    "bitbucket": false,
    "lcname": "znjson"
}
        
Elapsed time: 0.04214s