diff options
author | Nikita Sobolev <mail@sobolevn.me> | 2023-09-07 13:53:33 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2023-09-07 13:53:33 (GMT) |
commit | ac31f714c3e55a7951a9f3f9c823740c20c5d595 (patch) | |
tree | 9fb703eb10abff9fae7cd23f3dc1ff256b53924f | |
parent | 891236f48263e2d4c650b7a127fc9bffb8327807 (diff) | |
download | cpython-ac31f714c3e55a7951a9f3f9c823740c20c5d595.zip cpython-ac31f714c3e55a7951a9f3f9c823740c20c5d595.tar.gz cpython-ac31f714c3e55a7951a9f3f9c823740c20c5d595.tar.bz2 |
gh-107544: Add docs about `json.dumps(..., default=)` (#108259)
-rw-r--r-- | Doc/library/json.rst | 13 |
1 files changed, 12 insertions, 1 deletions
diff --git a/Doc/library/json.rst b/Doc/library/json.rst index 6c30593..b337b5f 100644 --- a/Doc/library/json.rst +++ b/Doc/library/json.rst @@ -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 |