Thanks to visit codestin.com
Credit goes to github.com

Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Sep 7, 2023

Conversation

sobolevn
Copy link
Member

@sobolevn sobolevn commented Aug 22, 2023

In my opinion, default= is a great alternative to custom JSONEncoder, compare how much easier it is than JSONEncoder:

    >>> import json
    >>> class ComplexEncoder(json.JSONEncoder):
    ...     def default(self, obj):
    ...         if isinstance(obj, complex):
    ...             return [obj.real, obj.imag]
    ...         # Let the base class default method raise the TypeError
    ...         return json.JSONEncoder.default(self, obj)
    ...
    >>> json.dumps(2 + 1j, cls=ComplexEncoder)
    '[2.0, 1.0]'

My example follows the same logic we have for object_hook in json.loads() part:

    >>> import json
    >>> def as_complex(dct):
    ...     if '__complex__' in dct:
    ...         return complex(dct['real'], dct['imag'])
    ...     return dct
    ...
    >>> json.loads('{"__complex__": true, "real": 1, "imag": 2}',
    ...     object_hook=as_complex)
    (1+2j)

So, now we would have a complete pair: with encoding and decoding.

Plus, this example answers all questions about the signature and features of the default function.


📚 Documentation preview 📚: https://cpython-previews--108259.org.readthedocs.build/

Copy link
Member

@JelleZijlstra JelleZijlstra left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good, left a suggestion to improve a nearby example.

@@ -60,6 +60,17 @@ Pretty printing::
"6": 7
}

Specializing JSON object encoding::
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It's out of scope for this PR, but while you're here what do you think of changing the example immediately above to encode {'6': 7, '4': 5} instead, so that it better showcases that sort_keys sorts the keys?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done! Good idea

@JelleZijlstra JelleZijlstra merged commit ac31f71 into python:main Sep 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs Documentation in the Doc dir skip news
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants