1. import json
  2. def load_user_records(filepath):
  3. """Loads user records from a JSON file."""
  4. try:
  5. with open(filepath, 'r') as f:
  6. user_records = json.load(f)
  7. return user_records
  8. except FileNotFoundError:
  9. print(f"Error: File not found at {filepath}")
  10. return []
  11. except json.JSONDecodeError:
  12. print(f"Error: Invalid JSON format in {filepath}")
  13. return []
  14. def validate_user_record(user):
  15. """Performs basic sanity checks on a user record."""
  16. if not isinstance(user, dict):
  17. print(f"Error: User record is not a dictionary: {user}")
  18. return False
  19. if 'user_id' not in user or not isinstance(user['user_id'], (int, str)):
  20. print(f"Error: Missing or invalid user_id: {user}")
  21. return False
  22. if 'email' not in user or not isinstance(user['email'], str):
  23. print(f"Error: Missing or invalid email: {user}")
  24. return False
  25. if not user['email'].contains('@'):
  26. print(f"Error: Invalid email format: {user}")
  27. return False
  28. if 'username' not in user or not isinstance(user['username'], str):
  29. print(f"Error: Missing or invalid username: {user}")
  30. return False
  31. if not user['username']:
  32. print(f"Error: Username cannot be empty: {user}")
  33. return False
  34. return True
  35. def process_user_records(filepath):
  36. """Loads, validates, and prints user records."""
  37. user_records = load_user_records(filepath)
  38. if not user_records:
  39. print("No user records to process.")
  40. return
  41. valid_records = []
  42. invalid_count = 0
  43. for user in user_records:
  44. if validate_user_record(user):
  45. valid_records.append(user)
  46. else:
  47. invalid_count += 1
  48. print(f"Total user records: {len(user_records)}")
  49. print(f"Valid user records: {len(valid_records)}")
  50. print(f"Invalid user records: {invalid_count}")
  51. # Optionally print the valid records
  52. # for record in valid_records:
  53. # print(record)
  54. if __name__ == "__main__":
  55. # Example usage:
  56. # Replace 'user_records.json' with your actual file path
  57. process_user_records('user_records.json')

Add your comment