json_serializable.py 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197
  1. import json
  2. import logging
  3. from string import Template
  4. from typing import Any, Dict, Type, TypeVar, Union
  5. T = TypeVar("T", bound="JSONSerializable")
  6. # NOTE: Through inheritance, all of our classes should be children of JSONSerializable. (highest level)
  7. # NOTE: The @register_deserializable decorator should be added to all user facing child classes. (lowest level)
  8. def register_deserializable(cls: Type[T]) -> Type[T]:
  9. """
  10. A class decorator to register a class as deserializable.
  11. When a class is decorated with @register_deserializable, it becomes
  12. a part of the set of classes that the JSONSerializable class can
  13. deserialize.
  14. Deserialization is in essence loading attributes from a json file.
  15. This decorator is a security measure put in place to make sure that
  16. you don't load attributes that were initially part of another class.
  17. Example:
  18. @register_deserializable
  19. class ChildClass(JSONSerializable):
  20. def __init__(self, ...):
  21. # initialization logic
  22. Args:
  23. cls (Type): The class to be registered.
  24. Returns:
  25. Type: The same class, after registration.
  26. """
  27. JSONSerializable.register_class_as_deserializable(cls)
  28. return cls
  29. class JSONSerializable:
  30. """
  31. A class to represent a JSON serializable object.
  32. This class provides methods to serialize and deserialize objects,
  33. as well as save serialized objects to a file and load them back.
  34. """
  35. _deserializable_classes = set() # Contains classes that are whitelisted for deserialization.
  36. def serialize(self) -> str:
  37. """
  38. Serialize the object to a JSON-formatted string.
  39. Returns:
  40. str: A JSON string representation of the object.
  41. """
  42. try:
  43. return json.dumps(self, default=self._auto_encoder, ensure_ascii=False)
  44. except Exception as e:
  45. logging.error(f"Serialization error: {e}")
  46. return "{}"
  47. @classmethod
  48. def deserialize(cls, json_str: str) -> Any:
  49. """
  50. Deserialize a JSON-formatted string to an object.
  51. If it fails, a default class is returned instead.
  52. Note: This *returns* an instance, it's not automatically loaded on the calling class.
  53. Example:
  54. app = App.deserialize(json_str)
  55. Args:
  56. json_str (str): A JSON string representation of an object.
  57. Returns:
  58. Object: The deserialized object.
  59. """
  60. try:
  61. return json.loads(json_str, object_hook=cls._auto_decoder)
  62. except Exception as e:
  63. logging.error(f"Deserialization error: {e}")
  64. # Return a default instance in case of failure
  65. return cls()
  66. @staticmethod
  67. def _auto_encoder(obj: Any) -> Union[Dict[str, Any], None]:
  68. """
  69. Automatically encode an object for JSON serialization.
  70. Args:
  71. obj (Object): The object to be encoded.
  72. Returns:
  73. dict: A dictionary representation of the object.
  74. """
  75. if hasattr(obj, "__dict__"):
  76. dct = obj.__dict__.copy()
  77. for key, value in list(
  78. dct.items()
  79. ): # We use list() to get a copy of items to avoid dictionary size change during iteration.
  80. try:
  81. # Recursive: If the value is an instance of a subclass of JSONSerializable,
  82. # serialize it using the JSONSerializable serialize method.
  83. if isinstance(value, JSONSerializable):
  84. serialized_value = value.serialize()
  85. # The value is stored as a serialized string.
  86. dct[key] = json.loads(serialized_value)
  87. # Custom rules (subclass is not json serializable by default)
  88. elif isinstance(value, Template):
  89. dct[key] = {"__type__": "Template", "data": value.template}
  90. # Future custom types we can follow a similar pattern
  91. # elif isinstance(value, SomeOtherType):
  92. # dct[key] = {
  93. # "__type__": "SomeOtherType",
  94. # "data": value.some_method()
  95. # }
  96. # NOTE: Keep in mind that this logic needs to be applied to the decoder too.
  97. else:
  98. json.dumps(value) # Try to serialize the value.
  99. except TypeError:
  100. del dct[key] # If it fails, remove the key-value pair from the dictionary.
  101. dct["__class__"] = obj.__class__.__name__
  102. return dct
  103. raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
  104. @classmethod
  105. def _auto_decoder(cls, dct: Dict[str, Any]) -> Any:
  106. """
  107. Automatically decode a dictionary to an object during JSON deserialization.
  108. Args:
  109. dct (dict): The dictionary representation of an object.
  110. Returns:
  111. Object: The decoded object or the original dictionary if decoding is not possible.
  112. """
  113. class_name = dct.pop("__class__", None)
  114. if class_name:
  115. if not hasattr(cls, "_deserializable_classes"): # Additional safety check
  116. raise AttributeError(f"`{class_name}` has no registry of allowed deserializations.")
  117. if class_name not in {cl.__name__ for cl in cls._deserializable_classes}:
  118. raise KeyError(f"Deserialization of class `{class_name}` is not allowed.")
  119. target_class = next((cl for cl in cls._deserializable_classes if cl.__name__ == class_name), None)
  120. if target_class:
  121. obj = target_class.__new__(target_class)
  122. for key, value in dct.items():
  123. if isinstance(value, dict) and "__type__" in value:
  124. if value["__type__"] == "Template":
  125. value = Template(value["data"])
  126. # For future custom types we can follow a similar pattern
  127. # elif value["__type__"] == "SomeOtherType":
  128. # value = SomeOtherType.some_constructor(value["data"])
  129. default_value = getattr(target_class, key, None)
  130. setattr(obj, key, value or default_value)
  131. return obj
  132. return dct
  133. def save_to_file(self, filename: str) -> None:
  134. """
  135. Save the serialized object to a file.
  136. Args:
  137. filename (str): The path to the file where the object should be saved.
  138. """
  139. with open(filename, "w", encoding="utf-8") as f:
  140. f.write(self.serialize())
  141. @classmethod
  142. def load_from_file(cls, filename: str) -> Any:
  143. """
  144. Load and deserialize an object from a file.
  145. Args:
  146. filename (str): The path to the file from which the object should be loaded.
  147. Returns:
  148. Object: The deserialized object.
  149. """
  150. with open(filename, "r", encoding="utf-8") as f:
  151. json_str = f.read()
  152. return cls.deserialize(json_str)
  153. @classmethod
  154. def register_class_as_deserializable(cls, target_class: Type[T]) -> None:
  155. """
  156. Register a class as deserializable. This is a classmethod and globally shared.
  157. This method adds the target class to the set of classes that
  158. can be deserialized. This is a security measure to ensure only
  159. whitelisted classes are deserialized.
  160. Args:
  161. target_class (Type): The class to be registered.
  162. """
  163. cls._deserializable_classes.add(target_class)