gh-69643: Fix sorting keys of different types in json - #156985
Open
serhiy-storchaka wants to merge 1 commit into
Open
gh-69643: Fix sorting keys of different types in json#156985serhiy-storchaka wants to merge 1 commit into
serhiy-storchaka wants to merge 1 commit into
Conversation
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>
Documentation build overview
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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, sosort_keys=Trueno longer fails together withskipkeys=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.