How to Create a Data Helper Class in Python for JSON Files
Build a beginner-friendly Python helper class to read, write, filter, and summarize JSON data files with clean, reusable methods.
Python code
54 linesimport json
from pathlib import Path
class DataHelper:
"""Simple beginner-friendly helper for reading and writing JSON data files."""
@staticmethod
def read_json(filename):
file_path = Path(filename)
if file_path.exists():
with file_path.open("r", encoding="utf-8") as f:
return json.load(f)
return []
@staticmethod
def write_json(filename, data):
file_path = Path(filename)
with file_path.open("w", encoding="utf-8") as f:
json.dump(data, f, indent=4)
return f"Saved {len(data)} records to {filename}"
@staticmethod
def filter_records(data, key, value):
return [record for record in data if record.get(key) == value]
@staticmethod
def summarize(data, key):
summary = {}
for record in data:
field_value = record.get(key, "unknown")
summary[field_value] = summary.get(field_value, 0) + 1
return summary
if __name__ == "__main__":
# Create example data
sample_data = [
{"id": 1, "category": "books", "price": 10},
{"id": 2, "category": "music", "price": 12},
{"id": 3, "category": "books", "price": 9},
]
# Save and reload data
print(DataHelper.write_json("data.json", sample_data))
loaded = DataHelper.read_json("data.json")
# Demonstrate filtering
books = DataHelper.filter_records(loaded, "category", "books")
print("Filtered books:", books)
# Demonstrate summarization
summary = DataHelper.summarize(loaded, "category")
print("Category summary:", summary)
Output
Saved 3 records to data.json
Filtered books: [{'id': 1, 'category': 'books', 'price': 10}, {'id': 3, 'category': 'books', 'price': 9}]
Category summary: {'books': 2, 'music': 1}
How it works
The DataHelper class uses static methods so you can call them without creating an instance. The read_json method safely checks if a file exists before loading, returning an empty list if not. write_json dumps data with indentation for readable output. Filtering uses a list comprehension with .get() to avoid KeyErrors, while summarize builds counts with a simple loop and dictionary updates. Path objects handle file paths cross-platform.
Common mistakes
- Using `json.load` instead of `json.loads` when reading from file objects
- Not using `.get()` on records, causing KeyError when a field is missing
- Overwriting existing data without checking file existence first
- Forgetting to specify encoding="utf-8" when opening files
Variations
- Use `json.loads(Path(filename).read_text())` instead of an explicit file open context
- Add error handling like `try/except` for invalid JSON or permission errors
Real-world use cases
- Scripting ETL loads where you parse JSON exports and normalize rows before database inserts.
- Building config-driven batch processes that read JSON settings files on startup.
- Creating test fixtures that generate and reload JSON datasets for database integration tests.
Sponsored
More from Database scaling & optimization
- Approximate Count with HyperLogLog in Python medium
- B-Tree Insert and In-Order Traversal in Python hard
- Broadcast a Small Reference Table in Python easy
- Build a Full Text Search Index in Python medium
- Build a Partial Index Mock in Python for Database Filtering easy
- Composite index leftmost prefix in Python medium
Keep learning
Related tutorials and quizzes for this topic.