import json
import csv
def import_user_data(data_source, data_format="json", encoding="utf-8"):
"""
Imports user data from a specified source (JSON or CSV).
Handles potential errors and edge cases.
Args:
data_source (str): Path to the data file.
data_format (str, optional): Format of the data file ("json" or "csv"). Defaults to "json".
encoding (str, optional): Encoding of the file. Defaults to "utf-8".
Returns:
list: A list of user data dictionaries. Returns an empty list if an error occurs.
"""
user_data = []
try:
if data_format.lower() == "json":
with open(data_source, 'r', encoding=encoding) as f:
try:
data = json.load(f)
if not isinstance(data, list):
print("Error: JSON data must be a list of objects.")
return []
for item in data:
if not isinstance(item, dict):
print("Error: Each element in JSON list must be a dictionary.")
return []
user_data.append(item)
except json.JSONDecodeError as e:
print(f"Error decoding JSON: {e}")
return []
elif data_format.lower() == "csv":
with open(data_source, 'r', encoding=encoding) as f:
reader = csv.DictReader(f)
for row in reader:
user_data.append(row)
else:
print("Error: Unsupported data format. Use 'json' or 'csv'.")
return []
except FileNotFoundError:
print(f"Error: File not found at {data_source}")
return []
except Exception as e:
print(f"An unexpected error occurred: {e}")
return []
return user_data
Add your comment