pyobjson - Python Object JSON Tool

Python Object JSON Tool pyobjson.base module.

Attributes:
  • __author__ (str) –

    Python package template author.

  • __email__ (str) –

    Python package template author email.

Classes:

Name Description
PythonObjectJson

Base Python Object with JSON serialization and deserialization compatibility.

PythonObjectJson

Bases: object

Base Python Object with JSON serialization and deserialization compatibility.

Methods:

Name Description
__init__

Instantiate the PythonObjectJson class with all keyword arguments.

serialize

Create a serializable dictionary from the class instance.

deserialize

Load data to a class instance from a serializable dictionary.

to_json_str

Serialize the class instance to a JSON string.

from_json_str

Load a class instance deserialized from a JSON string to the current class instance.

save_to_json_file

Save the class instance to a JSON file.

load_from_json_file

Load the class instance from a JSON file.

Source code in src/pyobjson/base.py
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
class PythonObjectJson(object):
    """Base Python Object with JSON serialization and deserialization compatibility."""

    def __init__(self, **kwargs):
        """Instantiate the PythonObjectJson class with all keyword arguments.

        Args:
            kwargs (dict): Key/value pairs to be passed to the PythonObjectJson class.

        """
        vars(self).update(kwargs)

    def __str__(self):
        return self.to_json_str()

    def __repr__(self):
        return (
            f"{derive_custom_object_key(self.__class__, as_lower=False)}"
            f"({','.join([f'{k}={v}' for k, v in vars(self).items() if k in getfullargspec(self.__init__).args])})"
        )

    def __eq__(self, other):
        return type(self) is type(other) and vars(self) == vars(other)

    def _base_subclasses(self) -> Dict[str, Type]:
        """Create a dictionary with lowercase keys derived from custom class names in camelcase mapped to their
        respective custom classes.

        Returns:
            dict[str, Type]: Dictionary with lowercase strings of all subclasses of PythonObjectJson as keys and
            subclasses as values.

        """
        # retrieve all class subclasses (and their nested subclasses) after base class
        return {derive_custom_object_key(cls): cls for cls in get_nested_subclasses(self.__class__.__mro__[-2])}

    def serialize(self) -> Dict[str, Any]:
        """Create a serializable dictionary from the class instance.

        Returns:
            dict[str, Any]: Serializable dictionary representing the class instance.

        """
        return serialize(self, list(self._base_subclasses().values()), [])

    def deserialize(self, serializable_dict: Dict[str, Any]) -> Any:
        """Load data to a class instance from a serializable dictionary.

        Args:
            serializable_dict (dict[str, Any]): Serializable dictionary representing the class instance.

        Returns:
            Any: Class instance deserialized from data dictionary.

        """
        return deserialize(serializable_dict, self._base_subclasses(), base_class_instance=self)

    def to_json_str(self) -> str:
        """Serialize the class instance to a JSON string.

        Returns:
            str: JSON string derived from the serializable version of the class instance.

        """
        return json.dumps(self.serialize(), ensure_ascii=False, indent=2)

    def from_json_str(self, json_str: str) -> None:
        """Load a class instance deserialized from a JSON string to the current class instance.

        Args:
            json_str (str): JSON string to be deserialized into the class instance.

        Returns:
            None

        """
        self.deserialize(json.loads(json_str))

    def save_to_json_file(self, json_file_path: Path) -> None:
        """Save the class instance to a JSON file.

        Args:
            json_file_path (Path): Target JSON file path to which the class instance will be saved.

        Returns:
            None

        """
        if not json_file_path.exists():
            json_file_path.parent.mkdir(parents=True, exist_ok=True)

        with open(json_file_path, "w", encoding="utf-8") as json_file_out:
            # TODO: fix incorrect file input type warning for json.dump from PyCharm bug https://youtrack.jetbrains.com/issue/PY-73050/openfile.txt-r-return-type-should-be-inferred-as-TextIOWrapper-instead-of-TextIO
            # noinspection PyTypeChecker
            json.dump(self.serialize(), json_file_out, ensure_ascii=False, indent=2)

    def load_from_json_file(self, json_file_path: Path) -> None:
        """Load the class instance from a JSON file.

        Args:
            json_file_path (Path): Target JSON file path from which the class instance will be loaded.

        Returns:
            None

        """
        if not json_file_path.exists():
            raise FileNotFoundError(f"File {json_file_path} does not exist. Unable to load saved data.")

        with open(json_file_path, "r", encoding="utf-8") as json_file_in:
            self.deserialize(json.load(json_file_in))

__init__

__init__(**kwargs)

Instantiate the PythonObjectJson class with all keyword arguments.

Parameters:
  • kwargs (dict, default: {} ) –

    Key/value pairs to be passed to the PythonObjectJson class.

Source code in src/pyobjson/base.py
24
25
26
27
28
29
30
31
def __init__(self, **kwargs):
    """Instantiate the PythonObjectJson class with all keyword arguments.

    Args:
        kwargs (dict): Key/value pairs to be passed to the PythonObjectJson class.

    """
    vars(self).update(kwargs)

serialize

serialize()

Create a serializable dictionary from the class instance.

Returns:
  • Dict[str, Any]

    dict[str, Any]: Serializable dictionary representing the class instance.

Source code in src/pyobjson/base.py
57
58
59
60
61
62
63
64
def serialize(self) -> Dict[str, Any]:
    """Create a serializable dictionary from the class instance.

    Returns:
        dict[str, Any]: Serializable dictionary representing the class instance.

    """
    return serialize(self, list(self._base_subclasses().values()), [])

deserialize

deserialize(serializable_dict)

Load data to a class instance from a serializable dictionary.

Parameters:
  • serializable_dict (dict[str, Any]) –

    Serializable dictionary representing the class instance.

Returns:
  • Any( Any ) –

    Class instance deserialized from data dictionary.

Source code in src/pyobjson/base.py
66
67
68
69
70
71
72
73
74
75
76
def deserialize(self, serializable_dict: Dict[str, Any]) -> Any:
    """Load data to a class instance from a serializable dictionary.

    Args:
        serializable_dict (dict[str, Any]): Serializable dictionary representing the class instance.

    Returns:
        Any: Class instance deserialized from data dictionary.

    """
    return deserialize(serializable_dict, self._base_subclasses(), base_class_instance=self)

to_json_str

to_json_str()

Serialize the class instance to a JSON string.

Returns:
  • str( str ) –

    JSON string derived from the serializable version of the class instance.

Source code in src/pyobjson/base.py
78
79
80
81
82
83
84
85
def to_json_str(self) -> str:
    """Serialize the class instance to a JSON string.

    Returns:
        str: JSON string derived from the serializable version of the class instance.

    """
    return json.dumps(self.serialize(), ensure_ascii=False, indent=2)

from_json_str

from_json_str(json_str)

Load a class instance deserialized from a JSON string to the current class instance.

Parameters:
  • json_str (str) –

    JSON string to be deserialized into the class instance.

Returns:
  • None

    None

Source code in src/pyobjson/base.py
87
88
89
90
91
92
93
94
95
96
97
def from_json_str(self, json_str: str) -> None:
    """Load a class instance deserialized from a JSON string to the current class instance.

    Args:
        json_str (str): JSON string to be deserialized into the class instance.

    Returns:
        None

    """
    self.deserialize(json.loads(json_str))

save_to_json_file

save_to_json_file(json_file_path)

Save the class instance to a JSON file.

Parameters:
  • json_file_path (Path) –

    Target JSON file path to which the class instance will be saved.

Returns:
  • None

    None

Source code in src/pyobjson/base.py
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
def save_to_json_file(self, json_file_path: Path) -> None:
    """Save the class instance to a JSON file.

    Args:
        json_file_path (Path): Target JSON file path to which the class instance will be saved.

    Returns:
        None

    """
    if not json_file_path.exists():
        json_file_path.parent.mkdir(parents=True, exist_ok=True)

    with open(json_file_path, "w", encoding="utf-8") as json_file_out:
        # TODO: fix incorrect file input type warning for json.dump from PyCharm bug https://youtrack.jetbrains.com/issue/PY-73050/openfile.txt-r-return-type-should-be-inferred-as-TextIOWrapper-instead-of-TextIO
        # noinspection PyTypeChecker
        json.dump(self.serialize(), json_file_out, ensure_ascii=False, indent=2)

load_from_json_file

load_from_json_file(json_file_path)

Load the class instance from a JSON file.

Parameters:
  • json_file_path (Path) –

    Target JSON file path from which the class instance will be loaded.

Returns:
  • None

    None

Source code in src/pyobjson/base.py
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
def load_from_json_file(self, json_file_path: Path) -> None:
    """Load the class instance from a JSON file.

    Args:
        json_file_path (Path): Target JSON file path from which the class instance will be loaded.

    Returns:
        None

    """
    if not json_file_path.exists():
        raise FileNotFoundError(f"File {json_file_path} does not exist. Unable to load saved data.")

    with open(json_file_path, "r", encoding="utf-8") as json_file_in:
        self.deserialize(json.load(json_file_in))