[issue34972] json dump silently converts int keys to string
My-Tien Nguyen
report at bugs.python.org
Sat Oct 13 10:56:17 EDT 2018
My-Tien Nguyen <my-tien.nguyen at ariadne.ai> added the comment:
I don’t think, “other languages do that too” is a good argument here. This would apply if behaving differently would break user expectation. But here we would do nothing more than explicitly inform the user of a relevant operation. If they already expected that behaviour, they can disregard the warning.
I don’t see how `parse_int`would help me here, I would need a `parse_str=int`, but then it would try to parse every string, and I don’t see the use case for that.
I would suggest a warning similar to this:
--- json/encoder.py
+++ json/encoder.py
@@ -1,6 +1,7 @@
"""Implementation of JSONEncoder
"""
import re
+import warnings
try:
from _json import encode_basestring_ascii as c_encode_basestring_ascii
@@ -353,7 +354,9 @@
items = sorted(dct.items(), key=lambda kv: kv[0])
else:
items = dct.items()
+ non_str_key = False
for key, value in items:
+ non_str_key = non_str_key or not isinstance(key, str)
if isinstance(key, str):
pass
# JavaScript is weakly typed for these, so it makes sense to
@@ -403,6 +406,8 @@
else:
chunks = _iterencode(value, _current_indent_level)
yield from chunks
+ if non_str_key:
+ warnings.warn("Encountered non-string key(s), converted to string.", RuntimeWarning)
if newline_indent is not None:
_current_indent_level -= 1
yield '\n' + _indent * _current_indent_level
----------
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue34972>
_______________________________________
More information about the Python-bugs-list
mailing list