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
| Function | Direction |
|---|---|
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.
import jsondata = {"name": "Aanya", "skills": ["python", "sql"], "active": True}text = json.dumps(data, indent=2) # pretty JSON stringback = json.loads(text) # → Python dict againwith open("data.json", "w") as f:json.dump(data, f, indent=2) # write to filewith 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:
# JSON object ↔ dict JSON array ↔ list# JSON string ↔ str JSON number ↔ int/float# true/false ↔ True/False null ↔ None
Key takeaways
- 01json.dumps/loads convert objects ↔ JSON strings; dump/load work with files.
- 02The "s" versions are for strings; the plain ones for files.
- 03JSON maps cleanly to dict, list, str, int/float, bool and None.
- 04Custom objects/dates/sets need converting first (or a default= function).
- 05JSON is safe and universal — prefer it over pickle for interchange.
