Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Python
Stage 5: Specialization

Part 08 / Topic 7 of 10

JSON

JSON (JavaScript Object Notation) is a text format for structured data (lists and dicts). Apps, APIs and config files use it everywhere. Think of it as a common language: a Python program, a website and a phone app can all read the same JSON file. Turning Python data into JSON text is called serializing; turning it back is deserializing.

Function Does
json.dumps(obj) Python → JSON string
json.loads(text) JSON string → Python
json.dump(obj, f) Python → JSON file
json.load(f) JSON file → Python

(The s means string.)

Real-world example: save and load a to-do list.

import json

todos = [{"title": "Pay bill", "done": False}, {"title": "Buy milk", "done": True}]

with open("demo_todos.json", "w", encoding="utf-8") as f:
    json.dump(todos, f, indent=2)

with open("demo_todos.json", encoding="utf-8") as f:
    loaded = json.load(f)
print(loaded[1]["title"], loaded[1]["done"])   # Buy milk True

print(json.dumps({"name": "Asha", "age": 21, "pass": True, "phone": None}))
# {"name": "Asha", "age": 21, "pass": true, "phone": null}
print(json.dumps({"city": "पुणे"}, ensure_ascii=False))   # {"city": "पुणे"}
Python JSON
dict object {}
list, tuple array []
str string "..." (double quotes only)
int, float number
True / False true / false
None null
  • indent=2 makes the file readable.
  • ensure_ascii=False keeps Hindi/emoji readable instead of escape codes like "\u092a\u0941...".
  • JSON cannot store datetime or set directly. Save dates as ISO strings (section 9).
  • Dict keys always become strings: {1: "a"} → {"1": "a"}.

🔍 Going deeper: a round trip is not always exact: tuples come back as lists and int keys come back as strings. json.dump(data, f, default=str) turns unknown types (like datetime) into strings instead of failing. Loading JSON from an untrusted file is safe; it only ever creates plain data, never runs code.

See examples/03_todo_json.py.

Read more: the official json documentation.

Done here? The practice set for Part 8 — 8 exercises with solutions — is on the part page.

Search the guide