Skip to content

Commit 5b66b96

Browse files
committed
Merge branch 'dev'
2 parents ca3c115 + 68419ce commit 5b66b96

File tree

1 file changed

+33
-1
lines changed

1 file changed

+33
-1
lines changed

docs/serialization.rst

Lines changed: 33 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,15 +34,47 @@ Example:
3434
To Json
3535
-------
3636

37+
Dump json of the text view.
38+
3739
In order to do safe json serialization, use the to_json() method.
3840

39-
Example:
41+
**Parameters**
42+
43+
default_mapping : dictionary(optional), a dictionary of mapping of different types to json types.
44+
45+
by default DeepDiff converts certain data types. For example Decimals into floats so they can be exported into json.
46+
If you have a certain object type that the json serializer can not serialize it, please pass the appropriate type
47+
conversion through this dictionary.
48+
49+
kwargs: Any other kwargs you pass will be passed on to Python's json.dumps()
50+
51+
52+
Example 1 Serialize custom objects:
53+
>>> class A:
54+
... pass
55+
...
56+
>>> class B:
57+
... pass
58+
...
59+
>>> t1 = A()
60+
>>> t2 = B()
61+
>>> ddiff = DeepDiff(t1, t2)
62+
>>> ddiff.to_json()
63+
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.
64+
65+
>>> default_mapping = {A: lambda x: 'obj A', B: lambda x: 'obj B'}
66+
>>> ddiff.to_json(default_mapping=default_mapping)
67+
'{"type_changes": {"root": {"old_type": "A", "new_type": "B", "old_value": "obj A", "new_value": "obj B"}}}'
68+
69+
70+
Example 2:
4071
>>> t1 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": [1, 2, 3]}}
4172
>>> t2 = {1: 1, 2: 2, 3: 3, 4: {"a": "hello", "b": "world\n\n\nEnd"}}
4273
>>> ddiff = DeepDiff(t1, t2, view='tree')
4374
>>> ddiff.to_json()
4475
'{"type_changes": {"root[4][\'b\']": {"old_type": "list", "new_type": "str", "old_value": [1, 2, 3], "new_value": "world\\n\\n\\nEnd"}}}'
4576

77+
4678
.. _to_json_pickle_label:
4779

4880
To Json Pickle

0 commit comments

Comments
 (0)