Use ensure_ascii deliberately for a text contract
Also published in our primary archive.
To make a JSON text contract deliberate, pass ensure_ascii=False when a human-readable fixture should contain café; leave it as True when an ASCII-only escaped representation is required. The default is True, so json.dumps("café") produces the JSON text "caf\\u00e9". With False, the output is "café". The json.dumps documentation specifies both behaviors and notes that the default escapes non-ASCII characters.
This example shows both exact serialized forms, then decodes them and prints the resulting Python string. Its assertions prove that the selected text representations are exact for this input and that both decode back to the same value. This lets a fixture test distinguish a presentation requirement from the underlying string value.
ensure_ascii=False does not choose a file encoding, make all output characters unescaped, or guarantee acceptance by every downstream system. JSON still escapes quotation marks, backslashes, and control characters as needed. Conversely, ASCII escaping can be useful for an explicitly ASCII-only transport representation, but it can make a manually read fixture less direct. No newer API is used; this example runs on Python 3.
AI assistance disclosure: this example was written with AI assistance and uses only an in-memory value.
Example
import json
value = "café"
escaped = json.dumps(value)
readable = json.dumps(value, ensure_ascii=False)
assert escaped == '"caf\\u00e9"'
assert readable == '"café"'
assert json.loads(escaped) == json.loads(readable) == value
print(escaped)
print(readable)
print(json.loads(readable))
Expected output:
"caf\u00e9"
"café"
café