Debian Codegraph @

docs/serialization.rst

raw
1 :doc:`/index`
2
3 .. _serialization_label:
4
5 Serialization
6 =============
7
8 .. _to_dict_label:
9
10 To Dict
11 -------
12
13 In order to convert the DeepDiff object into a normal Python dictionary, use the to_dict() method.
14 The result is always a text-view dictionary regardless of the original view used to create the DeepDiff object.
15
16 **Parameters**
17
18 verbose_level: int, default=None
19 Override the verbose_level for the serialized output.
20 When None, the behavior depends on the original view:
21
22 - If the original view is 'text', the verbose_level from DeepDiff initialization is used.
23 - If the original view is 'tree', verbose_level=2 is used to provide the most detailed output.
24
25 Valid values are 0, 1, or 2.
26
27 Example:
28 >>> t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 3]}}
29 >>> t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n\n\nEnd"}}
30 >>> ddiff = DeepDiff(t1, t2)
31 >>> ddiff.to_dict()
32 {'type_changes': {"root[4]['b']": {'old_type': <class 'list'>, 'new_type': <class 'str'>, 'old_value': [1, 2, 3], 'new_value': 'world\n\n\nEnd'}}}
33
34
35 When the original view is 'tree', to_dict() defaults to verbose_level=2 for the most detailed output:
36
37 Example:
38 >>> t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 3]}}
39 >>> t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n\n\nEnd"}}
40 >>> ddiff = DeepDiff(t1, t2, view='tree')
41 >>> ddiff.to_dict()
42 {'type_changes': {"root[4]['b']": {'old_type': <class 'list'>, 'new_type': <class 'str'>, 'old_value': [1, 2, 3], 'new_value': 'world\n\n\nEnd'}}}
43
44 You can also override the verbose_level:
45
46 Example:
47 >>> ddiff = DeepDiff(t1, t2, view='tree')
48 >>> ddiff.to_dict(verbose_level=0)
49 {'type_changes': {"root[4]['b']": {'old_type': <class 'list'>, 'new_type': <class 'str'>}}}
50
51 .. _to_json_label:
52
53 To Json
54 -------
55
56 Dump json of the text view.
57
58 In order to do safe json serialization, use the to_json() method.
59
60 **Parameters**
61
62 default_mapping : dictionary(optional), a dictionary of mapping of different types to json types.
63
64 by default DeepDiff converts certain data types. For example Decimals into floats so they can be exported into json.
65 If you have a certain object type that the json serializer can not serialize it, please pass the appropriate type
66 conversion through this dictionary.
67
68 verbose_level: int, default=None
69 Override the verbose_level for the serialized output. Same behavior as to_dict().
70
71 kwargs: Any other kwargs you pass will be passed on to Python's json.dumps()
72
73
74 Example 1 Serialize custom objects:
75 >>> class A:
76 ... pass
77 ...
78 >>> class B:
79 ... pass
80 ...
81 >>> t1 = A()
82 >>> t2 = B()
83 >>> ddiff = DeepDiff(t1, t2)
84 >>> ddiff.to_json()
85 TypeError: We do not know how to convert <__main__.A object at 0x10648> of type <class '__main__.A'> for json serialization. Please pass the default_mapping parameter with proper mapping of the object to a basic python type.
86
87 >>> default_mapping = {A: lambda x: 'obj A', B: lambda x: 'obj B'}
88 >>> ddiff.to_json(default_mapping=default_mapping)
89 '{"type_changes": {"root": {"old_type": "A", "new_type": "B", "old_value": "obj A", "new_value": "obj B"}}}'
90
91
92 Example 2:
93 >>> t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 3]}}
94 >>> t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n\n\nEnd"}}
95 >>> ddiff = DeepDiff(t1, t2, view='tree')
96 >>> ddiff.to_json()
97 '{"type_changes": {"root[4][\'b\']": {"old_type": "list", "new_type": "str", "old_value": [1, 2, 3], "new_value": "world\\n\\n\\nEnd"}}}'
98
99
100 .. _to_json_pickle_label:
101
102 To Json Pickle
103 --------------
104
105 If you want the original DeepDiff object to be serialized with all the bells and whistles, you can use the to_json_pickle() and from_json_pickle() in order to serialize and deserialize its results into json. Note that json_pickle is unsafe and json pickle dumps from untrusted sources should never be loaded. It is recommended not to use this serialization unless you have to.
106
107 .. note::
108 You need to install the `jsonpickle <https://github.com/jsonpickle/jsonpickle>`_ package to use the to_json_pickle() method.
109
110 Serialize and then deserialize back to deepdiff
111 >>> t1 = {1: 1, 2: 2, 3: 3}
112 >>> t2 = {1: 1, 2: "2", 3: 3}
113 >>> ddiff = DeepDiff(t1, t2)
114 >>> jsoned = ddiff.to_json_pickle()
115 >>> jsoned
116 '{"type_changes": {"root[2]": {"new_type": {"py/type": "builtins.str"}, "new_value": "2", "old_type": {"py/type": "builtins.int"}, "old_value": 2}}}'
117 >>> ddiff_new = DeepDiff.from_json_pickle(jsoned)
118 >>> ddiff == ddiff_new
119 True
120
121
122 .. _from_json_pickle_label:
123
124 From Json Pickle
125 ----------------
126
127 Load the diff object from the json pickle dump.
128 Take a look at the above :ref:`to_json_pickle_label` for an example.
129
130
131 .. _delta_to_flat_rows_label:
132
133 Delta Serialize To Flat Rows
134 ----------------------------
135
136 Sometimes, it is desired to serialize a :ref:`delta_label` object to a list of flat rows. For example, to store them in relation databases. In that case, you can use the Delta.to_flat_rows to achieve the desired outcome. The rows are named tuples and can be converted to dictionaries using `._asdict()`
137
138 >>> from pprint import pprint
139 >>> from deepdiff import DeepDiff, Delta
140 >>> t1 = {"key1": "value1"}
141 >>> t2 = {"field2": {"key2": "value2"}}
142 >>> diff = DeepDiff(t1, t2, verbose_level=2)
143 >>> pprint(diff, indent=2)
144 { 'dictionary_item_added': {"root['field2']": {'key2': 'value2'}},
145 'dictionary_item_removed': {"root['key1']": 'value1'}}
146 >>> delta = Delta(diff, bidirectional=True)
147 >>> flat_rows = delta.to_flat_rows()
148 >>> pprint(flat_rows, indent=2)
149 [ FlatDeltaRow(path=['field2', 'key2'], action='dictionary_item_added', value='value2'),
150 FlatDeltaRow(path=['key1'], action='dictionary_item_removed', value='value1')]
151
152 .. note::
153 When converting a delta to flat rows, nested dictionaries that have single keys in them are flattened too.
154 Notice that the diff object says
155
156 { 'dictionary_item_added': {"root['field2']": {'key2': 'value2'}}
157
158 but the flat row is:
159
160 FlatDeltaRow(path=['field2', 'key2'], action='dictionary_item_added', value='value2')
161
162 That means, when you recreate the delta from the flat rows, you need to set force=True to apply the delta:
163
164 >>> t1 + delta == t2
165 True
166 >>> t2 - delta == t1
167 True
168 >>> delta2 = Delta(flat_rows_list=flat_rows, bidirectional=True)
169 >>> t1 + delta2 == t2
170 Expected the old value for root['field2']['key2'] to be None but it is not found. Error found on: 'field2'
171 False. You may want to set force=True, especially if this delta is created by passing flat_rows_list or flat_dict_list
172 >>> t1 + delta
173 {'field2': {'key2': 'value2'}}
174 >>> t1 + delta2
175 {}
176 >>> delta2 = Delta(flat_rows_list=flat_rows, bidirectional=True, force=True) # We need to set force=True
177 >>> t1 + delta2
178 {'field2': {'key2': 'value2'}}
179 >>>
180
181
182
183 Flat Row Specs:
184
185
186 class FlatDataAction(str, enum.Enum):
187 values_changed = 'values_changed'
188 type_changes = 'type_changes'
189 set_item_added = 'set_item_added'
190 set_item_removed = 'set_item_removed'
191 dictionary_item_added = 'dictionary_item_added'
192 dictionary_item_removed = 'dictionary_item_removed'
193 iterable_item_added = 'iterable_item_added'
194 iterable_item_removed = 'iterable_item_removed'
195 iterable_item_moved = 'iterable_item_moved'
196 iterable_items_inserted = 'iterable_items_inserted' # opcode
197 iterable_items_deleted = 'iterable_items_deleted' # opcode
198 iterable_items_replaced = 'iterable_items_replaced' # opcode
199 iterable_items_equal = 'iterable_items_equal' # opcode
200 attribute_removed = 'attribute_removed'
201 attribute_added = 'attribute_added'
202 unordered_iterable_item_added = 'unordered_iterable_item_added'
203 unordered_iterable_item_removed = 'unordered_iterable_item_removed'
204
205
206 UnkownValueCode = 'unknown___'
207
208
209 class FlatDeltaRow(NamedTuple):
210 path: List
211 action: FlatDataAction
212 value: Optional[Any] = UnkownValueCode
213 old_value: Optional[Any] = UnkownValueCode
214 type: Optional[Any] = UnkownValueCode
215 old_type: Optional[Any] = UnkownValueCode
216 new_path: Optional[List] = None
217 t1_from_index: Optional[int] = None
218 t1_to_index: Optional[int] = None
219 t2_from_index: Optional[int] = None
220 t2_to_index: Optional[int] = None
221
222
223 .. _delta_to_flat_dicts_label:
224
225 Delta Serialize To Flat Dictionaries
226 ------------------------------------
227
228 Sometimes, it is desired to serialize a :ref:`delta_label` object to a list of flat dictionaries. For example, to store them in relation databases. In that case, you can use the Delta.to_flat_dicts to achieve the desired outcome.
229
230 Since None is a valid value, we use a special hard-coded string to signify "unknown": 'unknown___'
231
232 .. note::
233 Many new keys are added to the flat dicts in DeepDiff 7.0.0
234 You may want to use :ref:`delta_to_flat_rows_label` instead of flat dicts.
235
236 For example:
237
238 >>> from pprint import pprint
239 >>> from deepdiff import DeepDiff, Delta
240 >>> t1 = {"key1": "value1"}
241 >>> t2 = {"field2": {"key2": "value2"}}
242 >>> diff = DeepDiff(t1, t2, verbose_level=2)
243 >>> pprint(diff, indent=2)
244 { 'dictionary_item_added': {"root['field2']": {'key2': 'value2'}},
245 'dictionary_item_removed': {"root['key1']": 'value1'}}
246 >>> delta = Delta(diff, bidirectional=True)
247 >>> flat_dicts = delta.to_flat_dicts()
248 >>> pprint(flat_dicts, indent=2)
249 [ { 'action': 'dictionary_item_added',
250 'new_path': None,
251 'old_type': 'unknown___',
252 'old_value': 'unknown___',
253 'path': ['field2', 'key2'],
254 't1_from_index': None,
255 't1_to_index': None,
256 't2_from_index': None,
257 't2_to_index': None,
258 'type': 'unknown___',
259 'value': 'value2'},
260 { 'action': 'dictionary_item_removed',
261 'new_path': None,
262 'old_type': 'unknown___',
263 'old_value': 'unknown___',
264 'path': ['key1'],
265 't1_from_index': None,
266 't1_to_index': None,
267 't2_from_index': None,
268 't2_to_index': None,
269 'type': 'unknown___',
270 'value': 'value1'}]
271
272
273 Example 2:
274
275 >>> t3 = ["A", "B"]
276 >>> t4 = ["A", "B", "C", "D"]
277 >>> diff = DeepDiff(t3, t4, verbose_level=2)
278 >>> pprint(diff, indent=2)
279 {'iterable_item_added': {'root[2]': 'C', 'root[3]': 'D'}}
280 >>>
281 >>> delta = Delta(diff, bidirectional=True)
282 >>> flat_dicts = delta.to_flat_dicts()
283 >>> pprint(flat_dicts, indent=2)
284 [ { 'action': 'iterable_item_added',
285 'new_path': None,
286 'old_type': 'unknown___',
287 'old_value': 'unknown___',
288 'path': [2],
289 't1_from_index': None,
290 't1_to_index': None,
291 't2_from_index': None,
292 't2_to_index': None,
293 'type': 'unknown___',
294 'value': 'C'},
295 { 'action': 'iterable_item_added',
296 'new_path': None,
297 'old_type': 'unknown___',
298 'old_value': 'unknown___',
299 'path': [3],
300 't1_from_index': None,
301 't1_to_index': None,
302 't2_from_index': None,
303 't2_to_index': None,
304 'type': 'unknown___',
305 'value': 'D'}]
306
307
308 .. _delta_from_flat_dicts_label:
309
310 Delta Load From Flat Dictionaries
311 ------------------------------------
312
313 >>> from deepdiff import DeepDiff, Delta
314 >>> t3 = ["A", "B"]
315 >>> t4 = ["A", "B", "C", "D"]
316 >>> diff = DeepDiff(t3, t4, verbose_level=2)
317 >>> delta = Delta(diff, bidirectional=True)
318 >>> flat_dicts = delta.to_flat_dicts()
319 >>>
320 >>> delta2 = Delta(flat_dict_list=flat_dicts)
321 >>> t3 + delta == t4
322 True
323
324
325 Back to :doc:`/index`