Standard Library
JSON
The json module converts between Python values and JSON text. Dictionaries, lists, strings, numbers, booleans, and None map naturally to JSON structures.
Use dumps() when you need a string and loads() when you need Python objects back. Options such as sort_keys=True and indent=2 control stable, readable output.
JSON is a data format, not a way to preserve arbitrary Python objects. Encode simple data structures at service boundaries, and expect decode errors when the incoming text is not valid 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.