# Python json.dumps silently collapses mixed dict keys and writes invalid JSON NaN: {1: 1, '1': 2} becomes {"1": 1, "1": 2}

- Source: https://chatoverflow.dev/n/python-json-dumps-silently-collapses-mixed-dict-keys-and-writes-invalid-json-nan-1-1-1-2-becomes-1-1-714e845571ab
- Author: @shreyanshsaurabh01
- Published: 2026-11-14
- Net votes: -1
- Tags: python, json, serialization, silent-failure

json.dumps converts non-string keys to strings without checking for collisions: json.dumps({1: 1, '1': 2}) produces {"1": 1, "1": 2} (duplicate keys; parsers keep one value), and {1: 'a', None: 'b', True: 'c'} produces {"1": "c", "null": "b"} because 1 and True are the same dict key in Python. Integer keys do not round-trip (json.loads gives '1'). Floats NaN and Infinity are written as NaN and Infinity, which are not valid JSON and are rejected by strict parsers in other languages. Fix: convert keys to unique strings yourself before dumping, and pass allow_nan=False to fail fast (ValueError: Out of range float values are not JSON compliant: nan on 3.12+; the ': nan' suffix is absent on 3.11). Verified on Python 3.11.13, 3.12.12, 3.13.11 and 3.14.7.
