pyjson_translator


Namepyjson_translator JSON
Version 0.1.27 PyPI version JSON
download
home_pagehttps://github.com/moqimoqidea/pyjson_translator
SummaryA simple JSON to Python object translator
upload_time2024-09-01 03:54:20
maintainerNone
docs_urlNone
authormoqimoqidea
requires_python>=3.10
licenseNone
keywords json translator python
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            # pyjson_translator

A simple JSON to Python object translator.

## Installation

```bash
pip install -U pyjson_translator
```

Alternatively, you can use `poetry` for installation:

```bash
poetry add pyjson_translator@latest
```

For development purposes, use:

```bash
poetry install --with dev
```

Otherwise, use:

```bash
poetry install
```

## How to Use

### Serialization and Deserialization

The `pyjson_translator` package provides functions to serialize and deserialize various types of Python objects,
including primitive types, complex types, Pydantic models, SQLAlchemy models, and some simple classes.

When pyjson_translator encounters an unhandled type, it fails quickly and throws an exception.
This helps to quickly diagnose the problem and make adjustments as needed.

#### Basic Types

```python
from pyjson_translator.serialize import serialize_value, deserialize_value

int_value = 123
str_value = "hello"
bool_value = True

# Serialize basic types
serialized_int = serialize_value(123)
serialized_str = serialize_value("hello")
serialized_bool = serialize_value(True)

# Deserialize basic types
deserialize_value(serialized_int, int)
deserialize_value(serialized_str, str)
deserialize_value(serialized_bool, bool)
```

#### Complex Types

```python
from pyjson_translator.serialize import serialize_value, deserialize_value

complex_value = 3 + 4j

# Serialize complex types
# {'real': 3.0, 'imaginary': 4.0}
serialized_complex = serialize_value(complex_value)

# Deserialize basic types
# (3+4j)
deserialize_value(serialized_complex, complex)
```

#### Pydantic Models

```python
from pydantic import BaseModel
from pyjson_translator.serialize import serialize_value, deserialize_value


class ExampleModel(BaseModel):
    id: int
    name: str
    active: bool = True


example_model = ExampleModel(id=1, name="Example", active=True)

# Serialize Pydantic model
# {'id': 1, 'name': 'Example', 'active': True}
serialized_model = serialize_value(example_model)

# Deserialize Pydantic model
# id=1 name='Example' active=True
deserialized_model = deserialize_value(serialized_model, ExampleModel)
```

#### SQLAlchemy Models

```python
from pyjson_translator.serialize import serialize_value, deserialize_value
from pyjson_translator.db_sqlalchemy_instance import default_sqlalchemy_instance as db


class AddressClass(db.Model):
    __tablename__ = 'addresses_table'
    id = db.Column(db.Integer, primary_key=True)
    street = db.Column(db.String(100))
    city = db.Column(db.String(50))
    state = db.Column(db.String(20))
    zip = db.Column(db.String(10))
    user_id = db.Column(db.Integer, db.ForeignKey('users_table.id'), nullable=False)

class UserClass(db.Model):
    __tablename__ = 'users_table'
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(50), unique=True)
    email = db.Column(db.String(120), unique=True)
    address = db.relationship("AddressClass", backref="user", lazy='select', passive_deletes="all")

address_instance = AddressClass(id=1, street="123 Main St", city="New York", state="NY", zip="10001", user_id=1)
user_instance = UserClass(id=1, username="john_doe", email="john@example.com", address=[address_instance])

# Serialize SQLAlchemy model
# {'address': [{'city': 'New York',
#               'id': 1,
#               'state': 'NY',
#               'street': '123 Main St',
#               'zip': '10001'}],
#  'email': 'john@example.com',
#  'id': 1,
#  'username': 'john_doe'}
serialized_user = serialize_value(user_instance)

# Deserialize SQLAlchemy model
# {'address': [{'city': 'New York',
#               'id': 1,
#               'state': 'NY',
#               'street': '123 Main St',
#               'zip': '10001'}],
#  'email': 'john@example.com',
#  'id': 1,
#  'username': 'john_doe'}
deserialized_user = deserialize_value(serialized_user, UserClass)
```

#### Simple Classes

```python
from pyjson_translator.serialize import serialize_value, deserialize_value


class SimpleModel:
    def __init__(self, simple_id, name, active):
        self.simple_id = simple_id
        self.name = name
        self.active = active

    def __repr__(self):
        return f"<SimpleModel simple_id={self.simple_id}, name={self.name}, active={self.active}>"


example_model = SimpleModel(simple_id=1, name="Example", active=True)

# Serialize simple class
# {'simple_id': 1, 'name': 'Example', 'active': True}
serialized_simple_model = serialize_value(example_model)

# Deserialize simple class
# <SimpleModel simple_id=1, name=Example, active=True>
deserialized_simple_model = deserialize_value(serialized_simple_model, SimpleModel)
```

#### List with Simple Class

```python
from typing import List

from pyjson_translator.serialize import serialize_value, deserialize_value


class SimpleModel:
    def __init__(self, simple_id, name, active):
        self.simple_id = simple_id
        self.name = name
        self.active = active

    def __repr__(self):
        return f"<SimpleModel simple_id={self.simple_id}, name={self.name}, active={self.active}>"


example_model = SimpleModel(simple_id=1, name="Example", active=True)
example_model2 = SimpleModel(simple_id=2, name="Example", active=True)
simple_model_list = [example_model, example_model2]

# Serialize a list with simple class
# [{'simple_id': 1, 'name': 'Example', 'active': True}, {'simple_id': 2, 'name': 'Example', 'active': True}]
serialized_simple_model_list = serialize_value(simple_model_list)

# Deserialize simple class
# [<SimpleModel simple_id=1, name=Example, active=True>, <SimpleModel simple_id=2, name=Example, active=True>]
deserialized_simple_model_list = deserialize_value(serialized_simple_model_list, List[SimpleModel])
```

#### More Examples

For more examples and detailed usage, please refer to the `tests` directory in the repository.

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/moqimoqidea/pyjson_translator",
    "name": "pyjson_translator",
    "maintainer": null,
    "docs_url": null,
    "requires_python": ">=3.10",
    "maintainer_email": null,
    "keywords": "json, translator, python",
    "author": "moqimoqidea",
    "author_email": "moqimoqidea@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/a8/eb/d5a382a2023f55466344dff3dcb5c87920f17e4e5503462692e545a8d880/pyjson_translator-0.1.27.tar.gz",
    "platform": null,
    "description": "# pyjson_translator\n\nA simple JSON to Python object translator.\n\n## Installation\n\n```bash\npip install -U pyjson_translator\n```\n\nAlternatively, you can use `poetry` for installation:\n\n```bash\npoetry add pyjson_translator@latest\n```\n\nFor development purposes, use:\n\n```bash\npoetry install --with dev\n```\n\nOtherwise, use:\n\n```bash\npoetry install\n```\n\n## How to Use\n\n### Serialization and Deserialization\n\nThe `pyjson_translator` package provides functions to serialize and deserialize various types of Python objects,\nincluding primitive types, complex types, Pydantic models, SQLAlchemy models, and some simple classes.\n\nWhen pyjson_translator encounters an unhandled type, it fails quickly and throws an exception.\nThis helps to quickly diagnose the problem and make adjustments as needed.\n\n#### Basic Types\n\n```python\nfrom pyjson_translator.serialize import serialize_value, deserialize_value\n\nint_value = 123\nstr_value = \"hello\"\nbool_value = True\n\n# Serialize basic types\nserialized_int = serialize_value(123)\nserialized_str = serialize_value(\"hello\")\nserialized_bool = serialize_value(True)\n\n# Deserialize basic types\ndeserialize_value(serialized_int, int)\ndeserialize_value(serialized_str, str)\ndeserialize_value(serialized_bool, bool)\n```\n\n#### Complex Types\n\n```python\nfrom pyjson_translator.serialize import serialize_value, deserialize_value\n\ncomplex_value = 3 + 4j\n\n# Serialize complex types\n# {'real': 3.0, 'imaginary': 4.0}\nserialized_complex = serialize_value(complex_value)\n\n# Deserialize basic types\n# (3+4j)\ndeserialize_value(serialized_complex, complex)\n```\n\n#### Pydantic Models\n\n```python\nfrom pydantic import BaseModel\nfrom pyjson_translator.serialize import serialize_value, deserialize_value\n\n\nclass ExampleModel(BaseModel):\n    id: int\n    name: str\n    active: bool = True\n\n\nexample_model = ExampleModel(id=1, name=\"Example\", active=True)\n\n# Serialize Pydantic model\n# {'id': 1, 'name': 'Example', 'active': True}\nserialized_model = serialize_value(example_model)\n\n# Deserialize Pydantic model\n# id=1 name='Example' active=True\ndeserialized_model = deserialize_value(serialized_model, ExampleModel)\n```\n\n#### SQLAlchemy Models\n\n```python\nfrom pyjson_translator.serialize import serialize_value, deserialize_value\nfrom pyjson_translator.db_sqlalchemy_instance import default_sqlalchemy_instance as db\n\n\nclass AddressClass(db.Model):\n    __tablename__ = 'addresses_table'\n    id = db.Column(db.Integer, primary_key=True)\n    street = db.Column(db.String(100))\n    city = db.Column(db.String(50))\n    state = db.Column(db.String(20))\n    zip = db.Column(db.String(10))\n    user_id = db.Column(db.Integer, db.ForeignKey('users_table.id'), nullable=False)\n\nclass UserClass(db.Model):\n    __tablename__ = 'users_table'\n    id = db.Column(db.Integer, primary_key=True)\n    username = db.Column(db.String(50), unique=True)\n    email = db.Column(db.String(120), unique=True)\n    address = db.relationship(\"AddressClass\", backref=\"user\", lazy='select', passive_deletes=\"all\")\n\naddress_instance = AddressClass(id=1, street=\"123 Main St\", city=\"New York\", state=\"NY\", zip=\"10001\", user_id=1)\nuser_instance = UserClass(id=1, username=\"john_doe\", email=\"john@example.com\", address=[address_instance])\n\n# Serialize SQLAlchemy model\n# {'address': [{'city': 'New York',\n#               'id': 1,\n#               'state': 'NY',\n#               'street': '123 Main St',\n#               'zip': '10001'}],\n#  'email': 'john@example.com',\n#  'id': 1,\n#  'username': 'john_doe'}\nserialized_user = serialize_value(user_instance)\n\n# Deserialize SQLAlchemy model\n# {'address': [{'city': 'New York',\n#               'id': 1,\n#               'state': 'NY',\n#               'street': '123 Main St',\n#               'zip': '10001'}],\n#  'email': 'john@example.com',\n#  'id': 1,\n#  'username': 'john_doe'}\ndeserialized_user = deserialize_value(serialized_user, UserClass)\n```\n\n#### Simple Classes\n\n```python\nfrom pyjson_translator.serialize import serialize_value, deserialize_value\n\n\nclass SimpleModel:\n    def __init__(self, simple_id, name, active):\n        self.simple_id = simple_id\n        self.name = name\n        self.active = active\n\n    def __repr__(self):\n        return f\"<SimpleModel simple_id={self.simple_id}, name={self.name}, active={self.active}>\"\n\n\nexample_model = SimpleModel(simple_id=1, name=\"Example\", active=True)\n\n# Serialize simple class\n# {'simple_id': 1, 'name': 'Example', 'active': True}\nserialized_simple_model = serialize_value(example_model)\n\n# Deserialize simple class\n# <SimpleModel simple_id=1, name=Example, active=True>\ndeserialized_simple_model = deserialize_value(serialized_simple_model, SimpleModel)\n```\n\n#### List with Simple Class\n\n```python\nfrom typing import List\n\nfrom pyjson_translator.serialize import serialize_value, deserialize_value\n\n\nclass SimpleModel:\n    def __init__(self, simple_id, name, active):\n        self.simple_id = simple_id\n        self.name = name\n        self.active = active\n\n    def __repr__(self):\n        return f\"<SimpleModel simple_id={self.simple_id}, name={self.name}, active={self.active}>\"\n\n\nexample_model = SimpleModel(simple_id=1, name=\"Example\", active=True)\nexample_model2 = SimpleModel(simple_id=2, name=\"Example\", active=True)\nsimple_model_list = [example_model, example_model2]\n\n# Serialize a list with simple class\n# [{'simple_id': 1, 'name': 'Example', 'active': True}, {'simple_id': 2, 'name': 'Example', 'active': True}]\nserialized_simple_model_list = serialize_value(simple_model_list)\n\n# Deserialize simple class\n# [<SimpleModel simple_id=1, name=Example, active=True>, <SimpleModel simple_id=2, name=Example, active=True>]\ndeserialized_simple_model_list = deserialize_value(serialized_simple_model_list, List[SimpleModel])\n```\n\n#### More Examples\n\nFor more examples and detailed usage, please refer to the `tests` directory in the repository.\n",
    "bugtrack_url": null,
    "license": null,
    "summary": "A simple JSON to Python object translator",
    "version": "0.1.27",
    "project_urls": {
        "Documentation": "https://github.com/moqimoqidea/pyjson_translator#readme",
        "Homepage": "https://github.com/moqimoqidea/pyjson_translator",
        "Repository": "https://github.com/moqimoqidea/pyjson_translator",
        "Source": "https://github.com/moqimoqidea/pyjson_translator",
        "Tracker": "https://github.com/moqimoqidea/pyjson_translator/issues"
    },
    "split_keywords": [
        "json",
        " translator",
        " python"
    ],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "522650699221363da02f9d111e4c08b181f6f380fe20135b427fb5e4efdeda4f",
                "md5": "1a60a5552d7363dc0350a9f53d88b9fc",
                "sha256": "a488e4a18f9742d7327f47bb95491d0f645aa6a4b3f1d4f2a438730e9c64439d"
            },
            "downloads": -1,
            "filename": "pyjson_translator-0.1.27-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "1a60a5552d7363dc0350a9f53d88b9fc",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": ">=3.10",
            "size": 13142,
            "upload_time": "2024-09-01T03:54:19",
            "upload_time_iso_8601": "2024-09-01T03:54:19.316119Z",
            "url": "https://files.pythonhosted.org/packages/52/26/50699221363da02f9d111e4c08b181f6f380fe20135b427fb5e4efdeda4f/pyjson_translator-0.1.27-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a8ebd5a382a2023f55466344dff3dcb5c87920f17e4e5503462692e545a8d880",
                "md5": "d7bb2e53ca620c8ce8935beb569f01cf",
                "sha256": "7b75555d22a6220533f1fccd8e8d59f6962a5b0b0a41762cb94a20f33547ded7"
            },
            "downloads": -1,
            "filename": "pyjson_translator-0.1.27.tar.gz",
            "has_sig": false,
            "md5_digest": "d7bb2e53ca620c8ce8935beb569f01cf",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": ">=3.10",
            "size": 12367,
            "upload_time": "2024-09-01T03:54:20",
            "upload_time_iso_8601": "2024-09-01T03:54:20.916637Z",
            "url": "https://files.pythonhosted.org/packages/a8/eb/d5a382a2023f55466344dff3dcb5c87920f17e4e5503462692e545a8d880/pyjson_translator-0.1.27.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-09-01 03:54:20",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "moqimoqidea",
    "github_project": "pyjson_translator",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": false,
    "lcname": "pyjson_translator"
}
        
Elapsed time: 0.28393s