gh-107544: Add docs about `json.dumps(..., default=)` (#108259)

This commit is contained in:
Nikita Sobolev 2023-09-07 16:53:33 +03:00 committed by GitHub
parent 891236f482
commit ac31f714c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 12 additions and 1 deletions

View File

@ -54,12 +54,23 @@ Compact encoding::
Pretty printing::
>>> 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,
"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::
>>> import json