This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Can't use sort_keys in json.dumps with mismatched types
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.9
process
Status: closed Resolution: duplicate
Dependencies: Superseder: json dump fails for mixed-type keys when sort_keys is specified
View: 25457
Assigned To: Nosy List: josh.r, nicktimko, yoann934
Priority: normal Keywords:

Created on 2019-09-06 18:56 by yoann934, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Files
File name Uploaded Description Edit
json_bug_exemple.py yoann934, 2019-09-06 18:56
Pull Requests
URL Status Linked Edit
PR 15691 closed python-dev, 2019-09-07 09:56
Messages (3)
msg351268 - (view) Author: guillard (yoann934) * Date: 2019-09-06 18:56
If the dict included both str and int keys, sorted returns this error :
TypeError: '<' not supported between instances of 'int' and 'str'

It is a little bit problematic when used with default library behavior, as jsonify in Flask.

possible solution :
try:
    items = sorted(dct.items())
except(TypeError):
    items = sorted(dct.items(), key=lambda kv: str(kv[0]))
msg351269 - (view) Author: Nick Timkovich (nicktimko) * Date: 2019-09-06 19:47
It's not clear what you suggest, but it is likely better to alert the user that their keys have mismatched types than to suppress it by default.

Perhaps alongside the `sort_keys` argument, you would like a parameter that gets passed into `sorted()` when the items are sorted?

Perhaps an additional argument, or if sort_keys is a callable, use that as the `key` argument to sorted?

``` 
strange = {"1":"one", 2:"ii"}
json.dumps(strange, sort_keys=True, key=str)
json.dumps(strange, sort_keys=str)
# {"1": "one", 2: "ii"}
```
msg351270 - (view) Author: Josh Rosenberg (josh.r) * (Python triager) Date: 2019-09-06 20:13
This is an exact duplicate of #25457.
History
Date User Action Args
2022-04-11 14:59:19adminsetgithub: 82227
2019-09-07 09:56:29python-devsetpull_requests: + pull_request15379
2019-09-06 20:13:55josh.rsetstatus: open -> closed

superseder: json dump fails for mixed-type keys when sort_keys is specified

nosy: + josh.r
messages: + msg351270
resolution: duplicate
stage: resolved
2019-09-06 19:50:14nicktimkosetversions: + Python 3.9, - Python 3.7
components: + Library (Lib)
title: JSON sorting type error -> Can't use sort_keys in json.dumps with mismatched types
2019-09-06 19:47:23nicktimkosetnosy: + nicktimko
messages: + msg351269
2019-09-06 18:56:05yoann934create