Convert Python True, False, and None to JSON
Python and JSON name boolean and empty values differently. Let a serializer translate the values, not a search-and-replace script.
Python and JSON represent boolean and missing values with different spellings. Python uses True, False, and None. JSON uses true, false, and null.
| Python value | JSON value |
|---|---|
True | true |
False | false |
None | null |
Let the JSON encoder do the conversion
The reliable approach is to serialize a Python object rather than search and replace text:
import json
data = {"enabled": True, "archived": False, "deleted_at": None}
print(json.dumps(data))
# {"enabled": true, "archived": false, "deleted_at": null}
json.dumps() understands Python values and emits valid JSON. It also handles nested lists and dictionaries without changing text inside a string value.
Why replace() is risky
A simple text.replace("None", "null") can corrupt data. For instance, the string "None of these values" is ordinary text, not a null value. A serializer knows the difference between a value and characters inside a quoted string.
Likewise, replacing single quotes with double quotes can break escaped quotes and text such as don't. Parse the Python literal first if you have Python-style text, then write JSON with a serializer.
Reading JSON back into Python
data = json.loads('{"enabled": true, "deleted_at": null}')
print(data["enabled"]) # True
print(data["deleted_at"]) # None
json.loads() performs the reverse mapping as it parses valid JSON. It will reject Python syntax such as {'enabled': True}, because that is a Python representation rather than JSON.
Convert a pasted value safely
For the formal JSON syntax, see RFC 8259. Python’s supported encoder options are documented in the json module.