IDS peak ICV v1.3.0
Loading...
Searching...
No Matches
deserializer.py
Go to the documentation of this file.
1from __future__ import annotations
2import json
3from typing import TextIO, cast
4
5from ids_peak_common.serialization.iarchive import IArchive
6from ids_peak_icv.exceptions import IOException
8from ids_peak_icv.exceptions import NotSupportedException, CorruptedException
9from ids_peak_icv.serialization.serializer import SerializationType
10
11
13 """!
14 @brief
15 Deserializer for reading serialized data
16 and converting it into an `IArchive` object.
17
18 This class provides functionality to read data
19 from a supported serialization format
20 (currently, only JSON)
21 and reconstruct it as an `IArchive` object.
22
23 **Example**
24
25 from ids_peak_icv.serialization import Deserializer, SerializationType
26
27 deserializer = Deserializer(SerializationType.JSON)
28 with open("archive.json", "r") as f:
29 archive = deserializer.read(f)
30
31 id = archive.get("id", int)
32 name = archive.get("name", str)
33
34 @since ids_peak_icv 1.0
35
36 @ingroup ids_peak_icv_python_serialization
37 """
38
39 def __init__(self, serialization_type: SerializationType = SerializationType.JSON) -> None:
40 """!
41 @brief
42 Initializes a deserializer instance.
43
44 @param serialization_type: The format to use for deserialization.
45 Defaults to `SerializationType.JSON`.
46
47 @since ids_peak_icv 1.0
48 """
49 self._type = serialization_type
50
51 def read(self, stream: TextIO) -> IArchive:
52 """!
53 @brief
54 Reads serialized data from the specified stream
55 and deserializes it into an archive.
56
57 @param stream: The stream to read serialized data from.
58
59 @return An `IArchive` object containing the deserialized data.
60
61 @exception NotSupportedException: The serialization type is not supported.
62 @exception IOException: The parsing failed.
63 @exception CorruptedException: The format of the given data is invalid.
64
65 @since ids_peak_icv 1.0
66 """
67 if self._type != SerializationType.JSON:
68 raise NotSupportedException(f"Serialization type {self._type} is not supported.")
69
70 data = stream.read()
71 try:
72 parsed = json.loads(data)
73 except json.JSONDecodeError as e:
74 raise IOException(f"Failed to parse JSON: {e}")
75
76 archive = Archive()
77 self._populate_archive(archive, parsed)
78 return archive
79
80 def _populate_archive(self, archive: Archive, data: list | dict) -> None:
81 """!
82 @brief
83 Recursively populates an Archive with parsed JSON data.
84
85 @param archive: The archive to populate.
86 @param data: Parsed JSON data (dict, list, scalar).
87
88 @exception CorruptedException: The format of the given data is invalid.
89
90 @since ids_peak_icv 1.0
91 """
92 if not isinstance(data, dict):
93 raise CorruptedException("Root of serialized data must be a JSON object.")
94
95 for key, value in data.items():
96 if isinstance(value, dict):
97 nested = Archive()
98 self._populate_archive(nested, value)
99 archive.set(key, nested)
100 elif isinstance(value, list):
101 if value and isinstance(value[0], dict):
102 nested_list = []
103 for item in value:
104 nested = Archive()
105 self._populate_archive(nested, item)
106 nested_list.append(nested)
107 archive.set(key, cast(list[IArchive], nested_list))
108 else:
109 archive.set(key, value)
110 else:
111 archive.set(key, value)
Occurs when reading from a file or stream that is incomplete, damaged, or in an unexpected format.
Occurs when a file operation fails (e.g., missing file, insufficient permissions, or inaccessible dir...
Occurs when a requested operation is not implemented or supported (e.g., exporting to an unsupported ...
Definition exceptions.py:60
A key-value store with type checking, based on a dict.
Definition archive.py:11
Deserializer for reading serialized data and converting it into an IArchive object.
None _populate_archive(self, Archive archive, list|dict data)
Recursively populates an Archive with parsed JSON data.
None __init__(self, SerializationType serialization_type=SerializationType.JSON)
Initializes a deserializer instance.
IArchive read(self, TextIO stream)
Reads serialized data from the specified stream and deserializes it into an archive.