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.

Easy Python 3.9+ Aug 9, 2026 Data pipelines & processing 14 views 0 copies

Python code

33 lines
Python 3.9+
import 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

stdout
{
  "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

  1. Use pandas `DataFrame.apply` with a custom cleaning function for more complex transformations
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Data pipelines & processing

Related tutorials and quizzes for this topic.