Standard Library

JSON

json encodes Python values as JSON text and decodes them back.

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]}
Six type pairs bridge the JSON text boundary; each json value maps to one Python type.

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
True

Invalid 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

JSONDecodeError

Notes

See also

Run the complete example

Example code

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.