How to Create a JSON Data Helper in Python
A beginner-friendly DataHelper class that safely reads and writes JSON files with timestamps to a local data directory.
Python code
48 linesfrom datetime import datetime
from pathlib import Path
import json
class DataHelper:
"""Simple helper for reading/writing JSON files safely."""
def __init__(self, base_dir="data"):
self.base_dir = Path(base_dir)
self.base_dir.mkdir(exist_ok=True)
def save(self, filename, data):
"""Save data to a JSON file with timestamp."""
filepath = self.base_dir / f"{filename}.json"
record = {
"saved_at": datetime.now().isoformat(),
"data": data
}
with filepath.open("w") as f:
json.dump(record, f, indent=2)
return filepath
def load(self, filename):
"""Load data from a JSON file; return None if missing."""
filepath = self.base_dir / f"{filename}.json"
if not filepath.exists():
return None
with filepath.open("r") as f:
record = json.load(f)
return record["data"]
if __name__ == "__main__":
helper = DataHelper()
# Save example data
user = {"name": "Alice", "age": 30, "skills": ["python", "cloud"]}
filepath = helper.save("user", user)
print(f"Saved to: {filepath}")
# Load it back
loaded = helper.load("user")
print(f"Loaded data: {loaded}")
# Try loading non-existent file
missing = helper.load("nonexistent_file")
print(f"Missing file result: {missing}")
Output
Saved to: data/user.json
Loaded data: {'name': 'Alice', 'age': 30, 'skills': ['python', 'cloud']}
Missing file result: None
How it works
The DataHelper class wraps common JSON file operations in reusable methods. The save method uses datetime.now().isoformat() to attach a timestamp to each record, creating a lightweight audit trail. The load method checks for file existence before reading, returning None instead of raising an error—a pattern that simplifies downstream logic. Both methods use pathlib.Path for OS-agnostic file paths, and the constructor creates the base directory if it doesn't exist, making the helper drop-in ready for small projects or cloud function prototypes.
Common mistakes
- Forgetting that `save` requires a string filename without the `.json` extension—passing 'user.json' creates 'user.json.json'
- Assuming `load` never returns `None`; always handle the missing-file case in caller code
- Using `json.dump` without `indent=2` produces single-line files that are harder to debug
- Creating the base directory manually instead of letting the constructor handle it via `mkdir(exist_ok=True)`
Variations
- Add `encoding='utf-8'` to the file open calls for broader character support
- Use `dataclasses` or `pydantic` models to validate data before saving
Real-world use cases
- Persisting local configuration or session state in a small CLI tool that runs on cloud VMs.
- Caching API responses to disk in a lightweight cloud function to reduce repeated network calls.
- Storing user-submitted form data as JSON files in a serverless deployment for quick prototyping.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.