Title: Serialize dict with non-string keys to JSON — unexpected result
Type: behavior Stage: resolved
Components: Library (Lib) Versions: Python 3.6, Python 3.5, Python 2.7
Status: closed Resolution: wont fix
Dependencies: Superseder:
Assigned To: bob.ippolito Nosy List: anton-ryzhov, bob.ippolito, iritkatriel, rhettinger, serhiy.storchaka
Priority: low Keywords:

Created on 2016-04-09 20:03 by anton-ryzhov, last changed 2021-07-04 09:58 by iritkatriel. This issue is now closed.

Messages (4)
msg263108 - (view) Author: (anton-ryzhov) * Date: 2016-04-09 20:03
JSON doesn't allow to have non-sting keys in objects, so json.dumps converts its to string. But if several keys has one string representation — we'll get damaged result as follows:

>>> import json
>>> json.dumps({1: 2, "1": "2"})
'{"1": 2, "1": "2"}'

I think it should raise ValueError in this case.

I've tested this case on 2.7, 3.4 and on trunk version 3.6.
msg263110 - (view) Author: Serhiy Storchaka (serhiy.storchaka) * (Python committer) Date: 2016-04-09 20:20
See also .
msg263117 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2016-04-10 00:07
I think etrepum's comment on Aug 27, 2013 display's sound reasoning:
I expect that this error checking feature would be expensive to implement (both in runtime cost and lines of code). I think the most sensible thing to do would be to just mention this in the docs, or do nothing. In the past ~8 years, this is the only time this potential issue has ever been brought up here. It's not technically invalid JSON, but the decode semantics aren't well defined by the spec.

I think this should be closed as "not a bug" since the semantics aren't well defined and because currently deployed code may rely on the behavior which isn't unreasonable or shocking. In general, Python tools aim more for practicality than for lint-like advisories about all possible input oddities.
msg396492 - (view) Author: Irit Katriel (iritkatriel) * (Python committer) Date: 2021-06-24 14:41
This is documented, was added here:

If nobody objects I will close as won't fix.
Date User Action Args
2021-07-04 09:58:47iritkatrielsetstatus: pending -> closed
stage: resolved
2021-06-24 14:41:21iritkatrielsetstatus: open -> pending

nosy: + iritkatriel
messages: + msg396492

resolution: wont fix
2016-04-10 00:07:55rhettingersetpriority: normal -> low

nosy: + rhettinger, bob.ippolito
messages: + msg263117

assignee: bob.ippolito
2016-04-09 20:20:58serhiy.storchakasetnosy: + serhiy.storchaka

messages: + msg263110
versions: - Python 3.4
2016-04-09 20:03:30anton-ryzhovcreate