Context Managers & JSON Data

intermediate level · ~20 min · Module 9: File Handling & Serialization

Read/write files safely with open() and serialize complex Python dicts to JSON.

Learning objectives

  • Use with open() context manager to ensure proper file closing
  • Parse and generate JSON using json.loads() and json.dumps()

Lesson material

Working with JSON

JSON (JavaScript Object Notation) is standard for web data exchange.

Example code

import json

data = {"title": "PyMastery", "version": 1.0, "active": True}
json_str = json.dumps(data)
print("Serialized JSON:", json_str)

parsed = json.loads(json_str)
print("Parsed Title:", parsed["title"])

Practice exercise: JSON Processing

Import json. Given json string `s = '{"score": 95}'`, parse it to dict and print the value of `"score"`.

Test yourself with the Module 9: File Handling & Serialization quiz →

View the full Python curriculum →