import json
def load_user_records(filepath):
"""Loads user records from a JSON file."""
try:
with open(filepath, 'r') as f:
user_records = json.load(f)
return user_records
except FileNotFoundError:
print(f"Error: File not found at {filepath}")
return []
except json.JSONDecodeError:
print(f"Error: Invalid JSON format in {filepath}")
return []
def validate_user_record(user):
"""Performs basic sanity checks on a user record."""
if not isinstance(user, dict):
print(f"Error: User record is not a dictionary: {user}")
return False
if 'user_id' not in user or not isinstance(user['user_id'], (int, str)):
print(f"Error: Missing or invalid user_id: {user}")
return False
if 'email' not in user or not isinstance(user['email'], str):
print(f"Error: Missing or invalid email: {user}")
return False
if not user['email'].contains('@'):
print(f"Error: Invalid email format: {user}")
return False
if 'username' not in user or not isinstance(user['username'], str):
print(f"Error: Missing or invalid username: {user}")
return False
if not user['username']:
print(f"Error: Username cannot be empty: {user}")
return False
return True
def process_user_records(filepath):
"""Loads, validates, and prints user records."""
user_records = load_user_records(filepath)
if not user_records:
print("No user records to process.")
return
valid_records = []
invalid_count = 0
for user in user_records:
if validate_user_record(user):
valid_records.append(user)
else:
invalid_count += 1
print(f"Total user records: {len(user_records)}")
print(f"Valid user records: {len(valid_records)}")
print(f"Invalid user records: {invalid_count}")
# Optionally print the valid records
# for record in valid_records:
# print(record)
if __name__ == "__main__":
# Example usage:
# Replace 'user_records.json' with your actual file path
process_user_records('user_records.json')
Add your comment