Skip to main content
Albero Academy

JSON

Serialise Python objects to JSON and back — the language of APIs.

File Handling9 min

JSON (JavaScript Object Notation) is the lingua franca of data interchange — it's what web APIs speak and a common config format. Python's built-in json module converts cleanly between Python objects and JSON text.

Four functions to remember

FunctionDirection
json.dumps(obj)Object → JSON string
json.loads(s)JSON string → object
json.dump(obj, f)Object → JSON file
json.load(f)JSON file → object

The mnemonic: the s versions work with strings; the plain ones work with files.

json in practice
import json
data = {"name": "Aanya", "skills": ["python", "sql"], "active": True}
text = json.dumps(data, indent=2) # pretty JSON string
back = json.loads(text) # → Python dict again
with open("data.json", "w") as f:
json.dump(data, f, indent=2) # write to file
with open("data.json") as f:
loaded = json.load(f) # read from file

How types map

JSON maps directly onto Python's core types, which is why it's so convenient:

type correspondence
# JSON object ↔ dict JSON array ↔ list
# JSON string ↔ str JSON number ↔ int/float
# true/false ↔ True/False null ↔ None

Key takeaways

  1. 01json.dumps/loads convert objects ↔ JSON strings; dump/load work with files.
  2. 02The "s" versions are for strings; the plain ones for files.
  3. 03JSON maps cleanly to dict, list, str, int/float, bool and None.
  4. 04Custom objects/dates/sets need converting first (or a default= function).
  5. 05JSON is safe and universal — prefer it over pickle for interchange.

Finished this chapter?

Mark it complete to track your progress through Python.