Message253324
In Python 3, trying to json-dump a dict with keys of different types fails with a TypeError when sort_keys is specified:
python2.7
===========
Python 2.7.10 (default, May 29 2015, 10:02:30)
[GCC 4.8.4] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> json.dumps({1 : 42, "foo" : "bar", None : "nada"}, sort_keys = True)
'{"null": "nada", "1": 42, "foo": "bar"}'
python3.5
============
Python 3.5.0 (default, Oct 5 2015, 12:03:13)
[GCC 4.8.5] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import json
>>> json.dumps({1 : 42, "foo" : "bar", None : "nada"}, sort_keys = True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib64/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/lib64/python3.5/json/encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/lib64/python3.5/json/encoder.py", line 257, in iterencode
return _iterencode(o, 0)
TypeError: unorderable types: str() < int()
Note that the documentation explicitly allows keys of different, if basic, types:
If skipkeys is True (default: False), then dict keys that are not of a basic type (str, int, float, bool, None) will be skipped instead of raising a TypeError.
As all they keys are dumped as strings, a simple solution would be to sort after converting to strings. Looking closely at the output of Python 2, the sort order is a bit strange! |
|
Date |
User |
Action |
Args |
2015-10-22 08:01:01 | tanzer@swing.co.at | set | recipients:
+ tanzer@swing.co.at |
2015-10-22 08:01:01 | tanzer@swing.co.at | set | messageid: <1445500861.68.0.856599723102.issue25457@psf.upfronthosting.co.za> |
2015-10-22 08:01:01 | tanzer@swing.co.at | link | issue25457 messages |
2015-10-22 08:01:00 | tanzer@swing.co.at | create | |
|