pyfcstm.utils.json
JSON/YAML serialization utilities for persistent storage.
This module provides a lightweight interface for serializing and deserializing
objects to and from JSON and YAML formats. It defines a base class,
IJsonOp, that supplies file I/O helpers and a consistent contract for
converting objects to JSON-serializable structures.
The module contains the following main components:
IJsonOp- Base interface for JSON/YAML serialization operations
Example:
>>> class MyData(IJsonOp):
... def __init__(self, data):
... self.data = data
...
... def _to_json(self):
... return {"data": self.data}
...
... @classmethod
... def _from_json(cls, data):
... return cls(data["data"])
...
>>> obj = MyData([1, 2, 3])
>>> obj.to_json("example.json")
>>> loaded = MyData.read_json("example.json")
>>> loaded.data
[1, 2, 3]
Note
The serialization logic is defined by subclasses via _to_json() and
_from_json(). The base class only handles file I/O and validation.
T
- pyfcstm.utils.json.T = ~T
Type variable.
Usage:
T = TypeVar('T') # Can be anything A = TypeVar('A', str, bytes) # Must be str or bytes
Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function definitions. See class Generic for more information on generic types. Generic functions work as follows:
- def repeat(x: T, n: int) -> List[T]:
‘’’Return a list containing n references to x.’’’ return [x]*n
- def longest(x: A, y: A) -> A:
‘’’Return the longest of two strings.’’’ return x if len(x) >= len(y) else y
The latter example’s signature is essentially the overloading of (str, str) -> str and (bytes, bytes) -> bytes. Also note that if the arguments are instances of some subclass of str, the return type is still plain str.
At runtime, isinstance(x, T) and issubclass(C, T) will raise TypeError.
Type variables defined with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. See PEP 484 for more details. By default generic types are invariant in all type variables.
Type variables can be introspected. e.g.:
T.__name__ == ‘T’ T.__constraints__ == () T.__covariant__ == False T.__contravariant__ = False A.__constraints__ == (str, bytes)
Note that only type variables defined in global scope can be pickled.
IJsonOp
- class pyfcstm.utils.json.IJsonOp[source]
An interface class that provides JSON serialization/deserialization capabilities.
This class defines a common interface for objects that need to be serialized to and deserialized from JSON/YAML formats. Concrete classes must implement the
_to_json()and_from_json()methods.Example:
>>> class MyData(IJsonOp): ... def __init__(self, data): ... self.data = data ... ... def _to_json(self): ... return {"data": self.data} ... ... @classmethod ... def _from_json(cls, data): ... return cls(data["data"])
- classmethod from_json(data: Dict[str, Any]) T[source]
Create an instance from JSON data.
- Parameters:
data (dict) – JSON-formatted data
- Returns:
An instance of the class
- Return type:
- Raises:
TypeError – If the created object is not an instance of the class
- property json: Dict[str, Any]
Get the JSON representation of the object.
- Returns:
JSON-serializable representation of the object
- Return type:
dict
- classmethod read_json(json_file: str) T[source]
Create an instance by reading from a JSON file.
- Parameters:
json_file (str) – Path to the input JSON file
- Returns:
An instance of the class
- Return type:
- classmethod read_yaml(yaml_file: str) T[source]
Create an instance by reading from a YAML file.
- Parameters:
yaml_file (str) – Path to the input YAML file
- Returns:
An instance of the class
- Return type: