Selenium + Python · Lesson 9 of 43

0/43 done

Module 9: File & Data Handling

9. File Management, JSON Serialization & Context Managers

15 minlesson

Your task

Implement parse_json_safely(json_str: str) -> dict:

  1. In try block, return json.loads(json_str).
  2. If json.JSONDecodeError occurs, return an empty dictionary {}.

Write it in the editor, then press Check answer (Ctrl + Enter).

File Handling & JSON with Context Managers

python
import json

# Reading JSON test data:
with open("test_data/users.json", "r", encoding="utf-8") as f:
    users = json.load(f)

# Parsing JSON string from an API response:
response_json = json.loads('{"id": 101, "status": "active"}')
print(response_json["status"])

# Writing logs:
with open("logs/run.log", "a", encoding="utf-8") as log_file:
    log_file.write("Test completed successfully\n")

Key Takeaways & Walkthrough Summary

Test data lives in JSON and CSV files, and test logs are written to disk. In this lesson, you will master the 'with' statement for safe file handling, json.loads and json.dumps, and parsing test datasets. Let's manage test data files!

Part of the Selenium + Python course (Selenium with Python). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

Why use 'with open()' instead of f = open()?

The 'with' context manager guarantees the file stream is automatically closed even if an exception occurs inside the block.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Python
Skip