Standard Library
JSON
dumps() encodes Python data as JSON text. sort_keys=True keeps dictionary keys in a stable order for reproducible output.
Source
import json
payload = {"language": "Python", "versions": [3, 13], "stable": True, "missing": None}
text = json.dumps(payload, sort_keys=True)
print(text)Output
{"language": "Python", "missing": null, "stable": true, "versions": [3, 13]}Formatting options change the JSON text, not the Python value. indent=2 is useful for human-readable output.
Source
pretty = json.dumps({"language": "Python", "stable": True}, indent=2, sort_keys=True)
print(pretty.splitlines()[0])
print(pretty.splitlines()[1])Output
{
"language": "Python",loads() decodes JSON text back into Python values. JSON null becomes Python None.
Source
decoded = json.loads(text)
print(decoded["language"])
print(decoded["missing"] is None)Output
Python
TrueInvalid JSON raises JSONDecodeError, so input boundaries should handle decode failures explicitly.
Source
try:
json.loads("{bad json}")
except json.JSONDecodeError as error:
print(error.__class__.__name__)Output
JSONDecodeErrorNotes
dumps()returns a string;loads()accepts a string.- JSON
true,false, andnullbecome PythonTrue,False, andNone. - Use
sort_keys=Truewhen stable text output matters. - JSON only represents data shapes, not arbitrary Python objects or behavior.
See also
- prerequisite: Dictionaries
- prerequisite: TypedDict
- prerequisite: Strings
Run the complete example
Expected output
{"language": "Python", "missing": null, "stable": true, "versions": [3, 13]}
{
"language": "Python",
Python
True
JSONDecodeError
Execution time appears here after you run the example.