Modern QA2026JSON Parsing — tiles
Log inJoin
57 / 80 · 12 Programming for QA · Regex and Parsing← prev⊞ allnext →☰ Read as one page

7.6JSON Parsing

JSON is the universal data format for APIs. Fluent JSON handling is essential.

import json

# Parse API response
data = json.loads(response.text)
assert data["users"][0]["name"] == "Alice"

# Pretty print for debugging
print(json.dumps(data, indent=2))

# Validate nested structure
def validate_user_structure(user: dict):
    required = {"id", "name", "email", "created_at"}
    assert required.issubset(user.keys()), f"Missing: {required - user.keys()}"
    assert isinstance(user["id"], int)
    assert isinstance(user["name"], str) and len(user["name"]) > 0
    assert "@" in user["email"]

for user in data["users"]:
    validate_user_structure(user)

Handling JSON Edge Cases

# Empty response body
if response.text:
    data = response.json()
else:
    data = None

# Non-JSON response (HTML error page)
try:
    data = response.json()
except json.JSONDecodeError:
    pytest.fail(f"Response is not JSON: {response.text[:200]}")

# Large numbers (precision loss)
# JSON spec does not define number precision. Some APIs return IDs as strings.
user_id = data["id"]  # Could be int or string depending on API