1. import json
  2. import csv
  3. def import_user_data(data_source, data_format="json", encoding="utf-8"):
  4. """
  5. Imports user data from a specified source (JSON or CSV).
  6. Handles potential errors and edge cases.
  7. Args:
  8. data_source (str): Path to the data file.
  9. data_format (str, optional): Format of the data file ("json" or "csv"). Defaults to "json".
  10. encoding (str, optional): Encoding of the file. Defaults to "utf-8".
  11. Returns:
  12. list: A list of user data dictionaries. Returns an empty list if an error occurs.
  13. """
  14. user_data = []
  15. try:
  16. if data_format.lower() == "json":
  17. with open(data_source, 'r', encoding=encoding) as f:
  18. try:
  19. data = json.load(f)
  20. if not isinstance(data, list):
  21. print("Error: JSON data must be a list of objects.")
  22. return []
  23. for item in data:
  24. if not isinstance(item, dict):
  25. print("Error: Each element in JSON list must be a dictionary.")
  26. return []
  27. user_data.append(item)
  28. except json.JSONDecodeError as e:
  29. print(f"Error decoding JSON: {e}")
  30. return []
  31. elif data_format.lower() == "csv":
  32. with open(data_source, 'r', encoding=encoding) as f:
  33. reader = csv.DictReader(f)
  34. for row in reader:
  35. user_data.append(row)
  36. else:
  37. print("Error: Unsupported data format. Use 'json' or 'csv'.")
  38. return []
  39. except FileNotFoundError:
  40. print(f"Error: File not found at {data_source}")
  41. return []
  42. except Exception as e:
  43. print(f"An unexpected error occurred: {e}")
  44. return []
  45. return user_data

Add your comment