Skip to content

gh-69643: Fix sorting keys of different types in json - #156985

Open
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:json-bucket-sort
Open

gh-69643: Fix sorting keys of different types in json#156985
serhiy-storchaka wants to merge 1 commit into
python:mainfrom
serhiy-storchaka:json-bucket-sort

Conversation

@serhiy-storchaka

Copy link
Copy Markdown
Member

If the sorting fails, the items are now sorted by groups: strings, numbers (booleans are numbers too) and None. Unsupported keys are skipped or reported at this point, so sort_keys=True no longer fails together with skipkeys=True.

>>> json.dumps({None: 0, True: 1, 2: 2, 10.0: 4, 'a': 3}, sort_keys=True)
'{"a": 3, "true": 1, "2": 2, "10.0": 4, "null": 0}'

The grouping runs only after the sorting has failed, so dictionaries with keys of the same type are sorted as before, and the order of numeric keys does not change.

This is an alternative to GH-8011, which converts all keys to strings before sorting, and therefore changes the order of numeric keys.

json.dumps() and json.dump() with sort_keys=True failed for keys of
different basic types (str, int, float, bool and None), and for
unsupported keys skipped due to skipkeys.  Now keys of mixed types are
sorted by groups: strings, numbers (booleans are numbers too) and None.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
@read-the-docs-community

Copy link
Copy Markdown

Documentation build overview

📚 cpython-previews | 🛠️ Build #34408071 | 📁 Comparing 08e550c against main (e620377)

  🔍 Preview build  

2 files changed
± library/json.html
± whatsnew/changelog.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant