The json module accepts arbitrary strings for indent. Depending on the string and input data, this can produce invalid JSON or valid JSON with different values.
For example:
import json
data = [1, 2]
for indent in ["4", "1", "-", "1e", "1."]:
text = json.dumps(data, indent=indent)
print(repr(indent), json.loads(text))
'4' [41, 42]
'1' [11, 12]
'-' [-1, -2]
'1e' [10.0, 100.0]
'1.' [1.1, 1.2]
For a typical object such as {"name": "example", "values": [1, 2]}, those same strings produce invalid JSON instead. This was reproduced on CPython 3.14.5 on Windows, including the Python encoder fallback.
Reproducible test
The test compares against serialization without indentation, excluding normal JSON conversions from the comparison.
import json
documents = {
"object": {
"name": "example",
"active": True,
"values": [1, 2],
"metadata": None,
},
"numeric_array": [1, 2],
}
indents = [
None, 4, 0, -1, "", " ", "\t", "\n", "\r",
" \t\n\r", "4", "0", "1", " 4", "-", "-1",
"1e", "1.", "0.", "banana", "true", "null",
"\f", "\v", "\u00a0", "\u2003",
]
for name, data in documents.items():
baseline = json.loads(json.dumps(data))
for indent in indents:
text = json.dumps(data, indent=indent)
try:
decoded = json.loads(text)
except json.JSONDecodeError:
status = "invalid JSON"
else:
status = (
"unchanged"
if decoded == baseline
else f"changed to {decoded!r}"
)
print(f"{name}: indent={indent!r}: {status}")
Proposal and compatibility
bpo-41998 / GH-86164 previously reported field injection through indent and proposed converting it to an integer. It was closed as “not a bug,” with validation considered the application’s responsibility.
Would a narrower change be worth considering: retain string indentation, but reject characters outside JSON’s whitespace set—space, tab, LF and CR—as defined in RFC 8259?
Empty strings, combinations of those four characters, integers and None would remain supported. str.isspace() would be too permissive because it accepts additional characters outside JSON’s whitespace set.
I recognize this would narrow documented behavior. Are there use cases for non-whitespace indentation that make this restriction undesirable, or would preventing these effects justify a compatibility transition?