How to Clean and Format Data in Python
This code loads JSON data, cleans records by removing empty fields and normalizing text, then summarizes the results with counts and unique keys.
Python code
33 linesimport json
from pathlib import Path
def load_data(filepath: str) -> dict:
"""Load JSON data from a file."""
with Path(filepath).open("r", encoding="utf-8") as f:
return json.load(f)
def clean_records(records: list[dict]) -> list[dict]:
"""Remove empty fields and normalize text to lowercase."""
cleaned = []
for record in records:
filtered = {k: str(v).strip().lower() for k, v in record.items() if v}
if filtered:
cleaned.append(filtered)
return cleaned
def summarize(records: list[dict]) -> dict:
"""Return counts and unique keys across records."""
keys = set()
for record in records:
keys.update(record.keys())
return {"record_count": len(records), "unique_keys": sorted(keys)}
if __name__ == "__main__":
raw = load_data("data.json")
cleaned = clean_records(raw["users"])
summary = summarize(cleaned)
print(json.dumps(summary, indent=2))
Output
{
"record_count": 2,
"unique_keys": [
"age",
"email",
"name"
]
}
How it works
The Path.open method reads files with proper UTF-8 encoding handling. The clean_records function uses a dictionary comprehension with a conditional if v to filter out falsy values like empty strings and None. The str(v).strip().lower() chain normalizes all text values, making data consistent for downstream processing. The summarize function collects all unique keys across records using a set, providing a quick overview of the data structure. Using list[dict] type hints makes the code self-documenting and IDE-friendly.
Common mistakes
- Forgetting to strip and normalize text, leading to inconsistent data comparisons
- Using `json.load` on a file object instead of `json.loads` on a string when handling file content
- Assuming all records have the same keys without checking for missing fields
Variations
- Use pandas `DataFrame.apply` with a custom cleaning function for more complex transformations
- Add a `try/except` block around `json.load` to handle malformed JSON files gracefully
Real-world use cases
- Preprocessing user data from a JSON export before loading into a database
- Normalizing CSV data imported from external partners for consistent storage
- Preparing configuration data from multiple sources for comparison and merging
Sponsored
More from Data pipelines & processing
- Add a UUID Surrogate Key to Each Row in a CSV with Python easy
- Attach Source File Metadata to Records in Python easy
- Build a Python Utility That Detects Duplicate Records Across Multiple Excel Sheets medium
- Check Null Rate Threshold in PySpark DataFrame medium
- Count Records Processed per Category in Python easy
- Create Data Helper Functions in Python for Beginners easy
Keep learning
Related tutorials and quizzes for this topic.