gh-107544: Add docs about json.dumps(..., default=)
(#108259)
This commit is contained in:
parent
891236f482
commit
ac31f714c3
@ -54,12 +54,23 @@ Compact encoding::
|
|||||||
Pretty printing::
|
Pretty printing::
|
||||||
|
|
||||||
>>> import json
|
>>> import json
|
||||||
>>> print(json.dumps({'4': 5, '6': 7}, sort_keys=True, indent=4))
|
>>> print(json.dumps({'6': 7, '4': 5}, sort_keys=True, indent=4))
|
||||||
{
|
{
|
||||||
"4": 5,
|
"4": 5,
|
||||||
"6": 7
|
"6": 7
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Specializing JSON object encoding::
|
||||||
|
|
||||||
|
>>> import json
|
||||||
|
>>> def custom_json(obj):
|
||||||
|
... if isinstance(obj, complex):
|
||||||
|
... return {'__complex__': True, 'real': obj.real, 'imag': obj.imag}
|
||||||
|
... raise TypeError(f'Cannot serialize object of {type(obj)}')
|
||||||
|
...
|
||||||
|
>>> json.dumps(1 + 2j, default=custom_json)
|
||||||
|
'{"__complex__": true, "real": 1.0, "imag": 2.0}'
|
||||||
|
|
||||||
Decoding JSON::
|
Decoding JSON::
|
||||||
|
|
||||||
>>> import json
|
>>> import json
|
||||||
|
Loading…
x
Reference in New Issue
Block a user