Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit ac31f71

Browse files
authored
gh-107544: Add docs about json.dumps(..., default=) (#108259)
1 parent 891236f commit ac31f71

File tree

1 file changed

+12
-1
lines changed

1 file changed

+12
-1
lines changed

Doc/library/json.rst

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,12 +54,23 @@ Compact encoding::
5454
Pretty printing::
5555

5656
>>> import json
57-
>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
57+
>>> print(json.dumps({'6': 7, '4': 5}, sort_keys=True, indent=4))
5858
{
5959
"4": 5,
6060
"6": 7
6161
}
6262

63+
Specializing JSON object encoding::
64+
65+
>>> import json
66+
>>> def custom_json(obj):
67+
... if isinstance(obj, complex):
68+
... return {'__complex__': True, 'real': obj.real, 'imag': obj.imag}
69+
... raise TypeError(f'Cannot serialize object of {type(obj)}')
70+
...
71+
>>> json.dumps(1 + 2j, default=custom_json)
72+
'{"__complex__": true, "real": 1.0, "imag": 2.0}'
73+
6374
Decoding JSON::
6475

6576
>>> import json

0 commit comments

Comments
 (0)