9. File Management, JSON Serialization & Context Managers

File Handling & JSON with Context Managers

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")

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 {}.
πŸ’‘Common doubts
Did you like the problem?
Lesson 9 of 37
Python
Loading code editor…
Next