From ac31f714c3e55a7951a9f3f9c823740c20c5d595 Mon Sep 17 00:00:00 2001 From: Nikita Sobolev Date: Thu, 7 Sep 2023 16:53:33 +0300 Subject: [PATCH] gh-107544: Add docs about `json.dumps(..., default=)` (#108259) --- Doc/library/json.rst | 13 ++++++++++++- 1 file changed, 12 insertions(+), 1 deletion(-) diff --git a/Doc/library/json.rst b/Doc/library/json.rst index 6c305938177..b337b5f9960 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