MOD-24 · Sequence #24 · Standard Library

Python JSON & Regular Expressions

JSON is the ubiquitous data exchange format on the web, handled via json.loads/dumps. Regular expressions (the `re` module) provide pattern matching for data validation, tokenization, and web scraping.

Live Interactive Code Snippet (Python 3.12 CPython WASM) Open in Practice Mode →
import json, re
data = json.loads('{"name": "Alice", "age": 20}')
pattern = r"\d+"
print(re.findall(pattern, "Student 42 scored 98 points"))

Core Principles & Mental Models

1. JSON Serialization & Deserialization

dumps/loads vs. dump/load

  • `json.loads(str)`: Deserializes a JSON string into Python dictionaries, lists, booleans, and numbers.
  • `json.dumps(obj)`: Serializes a Python data structure into a JSON-formatted string.
  • Methods without the "s" (`json.load(file)` and `json.dump(obj, file)`) work directly with file streams.
import json
student = {"name": "Grace", "enrolled": True, "gpa": 3.88}
# Serialize to formatted string
json_str = json.dumps(student, indent=2)
print("JSON output:\n" + json_str)
# Deserialize back
obj = json.loads(json_str)
print("Parsed name:", obj["name"])
💡 Key Takeaway: The "s" in json.dumps/loads stands for String.

2. Regular Expressions with the re Module

Patterns, Matches, and Raw Strings

  • Always use raw strings `r"..."` for regex patterns so backslashes (\d, \w) are not interpreted as escape sequences by Python.
  • `re.search(pattern, text)`: Finds the first match anywhere in the string.
  • `re.findall(pattern, text)`: Returns all non-overlapping matches as a list of strings.
  • `re.sub(pattern, replacement, text)`: Replaces occurrences matching pattern.
import re
text = "CS101 score 94, CS102 score 88, CS201 score 99"
# Extract all two or three-digit numbers
scores = re.findall(r"\b\d{2,3}\b", text)
print("Extracted scores:", scores)
💡 Key Takeaway: Always use raw string literals r"..." when writing regex patterns in Python.

Interactive Walkthrough Examples

Email Format Validation with Regex (Intermediate)

Using re.match and capture groups to validate institutional email addresses.

import re

email_pattern = r"^([a-zA-Z0-9_.+-]+)@([a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+)
quot; test_emails = ["[email protected]", "invalid-email@", "[email protected]"] for email in test_emails: match = re.search(email_pattern, email) if match: username, domain = match.groups() print(f"Valid: {email} [User: {username}, Domain: {domain}]") else: print(f"Invalid: {email}")

Explanation: Capture groups `(...)` extract matching sub-components into tuples.

Common Misconceptions & Exam Traps

Common Pitfall: Omitting Raw String Prefix (`r"..."`) in Regex Patterns

Python string escape rules process backslashes before passing them to the re module.

Buggy Code
import re
# In non-raw string, "\b" is interpreted as ASCII backspace char (0x08)!
pattern = "\bword\b"
# Fails to match word boundaries properly
Correct Solution
pattern = r"\bword\b"  # Raw string preserves literal backslashes for the regex engine

Exam Trap Note: Always start regular expression patterns with r"..." to avoid subtle escaping bugs.

Conceptual Knowledge Self-Check Quiz

Q1: What is the difference between `json.load()` and `json.loads()`?

  1. There is no difference
  2. json.load reads from a file stream, json.loads reads from a string
  3. json.load handles binary, json.loads handles unicode
  4. json.load is deprecated

`json.load()` reads from a file-like object; `json.loads()` reads from a string.

Algorithmic Practice Challenges

Idiomatic Best Practices

  • ✅ Use `re.compile(pattern)` when running the same regex pattern repeatedly in loops.
  • ✅ Handle `TypeError: Object of type X is not JSON serializable` by providing a custom `default=` encoder to `json.dumps()`.

All 26 Curriculum Modules