How to Count JSON Records in Python

Read a JSON file and count the number of top-level records, handling both list and dictionary structures.

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

Python code

35 lines
Python 3.9+
import json
from pathlib import Path

def count_records(json_file):
    """Count top-level records in a JSON file."""
    with open(json_file, "r") as f:
        data = json.load(f)
    
    # Handle both list of records and dict of records
    if isinstance(data, list):
        return len(data)
    elif isinstance(data, dict):
        # If dict values are themselves dicts, count them as records
        # Adjust this condition based on your data structure
        return len([k for k, v in data.items() if isinstance(v, dict)])
    else:
        raise ValueError("Unsupported JSON structure")

if __name__ == "__main__":
    # Dry run sample: create a small test file
    sample_data = [
        {"id": 1, "name": "alice"},
        {"id": 2, "name": "bob"},
        {"id": 3, "name": "carol"}
    ]
    
    test_path = Path("records.json")
    with open(test_path, "w") as f:
        json.dump(sample_data, f)
    
    count = count_records(test_path)
    print(f"Records found: {count}")
    
    # Clean up the temp file
    test_path.unlink()

Output

stdout
Records found: 3

How it works

The json.load function reads the entire JSON file and converts it to native Python objects. The function then checks if the loaded data is a list or a dictionary. For a list, it returns the length directly. For a dictionary, it counts the values that are themselves dictionaries, a common pattern for record collections. The if __name__ == "__main__" guard ensures the sample code only runs when the script is executed directly.

Common mistakes

  • Using `json.loads` on a file object instead of `json.load`
  • Assuming data is always a list when it might be a dict
  • Not handling empty files or invalid JSON

Variations

  1. Use `pathlib.Path.read_text` and `json.loads` for a one-liner approach
  2. Count all keys in a dict regardless of value type if each key represents a record

Real-world use cases

  • Quickly verify the number of records in an exported JSON dataset before running a full ETL job.
  • Count API response records in a test suite to confirm the endpoint returned the expected batch size.
  • Check the size of a JSON config file's entries before loading them into an application at startup.

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.