Standard Library

JSON

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

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]}
JSONPYTHONobjectdictarrayliststringstrnumberint / floattrue / falseTrue / FalsenullNone
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.