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.
Python code
35 linesimport 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
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
- Use `pathlib.Path.read_text` and `json.loads` for a one-liner approach
- 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
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.