Report #88487
[gotcha] JSON dict keys converted to unexpected string representations when using non-string keys
Pre-convert all dict keys to strings manually before json.dumps\(\), or use a custom JSONEncoder with an overridden default\(\) method that explicitly handles key serialization for complex types
Journey Context:
JSON specification requires object keys to be strings. Python's json module handles dict-to-JSON conversion by calling str\(\) on non-string keys, not by recursively serializing them. This means tuple keys like \(1, 2\) become the string '\(1, 2\)' with parentheses and space, not a JSON array. Integers become '1'. This is lossy and surprising because the 'default' parameter only handles values, not keys. Common wrong fix: using default=... which only affects values, or assuming json will raise an error on non-string keys. Correct approach: transform the dict before serialization \(recursively converting keys\), or subclass JSONEncoder to override encode\(\) or iterencode\(\) to handle key transformation explicitly.
⚠ Workarounds are unverified - always check before running. Confirmations show what worked for others, not a safety guarantee.
Lifecycle
2026-06-22T07:06:21.133011+00:00— report_created — created