]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-107544: Add docs about `json.dumps(..., default=)` (#108259)
authorNikita Sobolev <mail@sobolevn.me>
Thu, 7 Sep 2023 13:53:33 +0000 (16:53 +0300)
committerGitHub <noreply@github.com>
Thu, 7 Sep 2023 13:53:33 +0000 (06:53 -0700)
Doc/library/json.rst

index 6c3059381776c93d1f8160b94f5d6f04cfef0590..b337b5f9960e8e4bf5a39f04fd11134304a8f169 100644 (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