import json
import logging
import time
from typing import List, Dict, Any
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def process_json_batch(json_list: List[Dict[str, Any]]):
"""
Processes a batch of JSON objects, handling potential errors.
Args:
json_list: A list of JSON objects (dictionaries).
Returns:
A list of results. Each result corresponds to the processing of a JSON object.
Returns an empty list if json_list is empty.
"""
if not json_list:
logging.info("Empty JSON list provided. Returning empty result list.")
return []
results = []
for i, json_obj in enumerate(json_list):
try:
# Simulate processing (replace with your actual logic)
start_time = time.time()
result = process_single_json(json_obj, i)
end_time = time.time()
logging.info(f"Processed JSON object {i+1} in {end_time - start_time:.4f} seconds.")
results.append(result)
except Exception as e:
logging.error(f"Error processing JSON object {i+1}: {e}")
results.append({"error": str(e), "index": i}) # store error info
return results
def process_single_json(json_obj: Dict[str, Any], index: int) -> Dict[str, Any]:
"""
Processes a single JSON object.
Args:
json_obj: A single JSON object (dictionary).
index: The index of the JSON object in the batch.
Returns:
The result of processing the JSON object.
Raises:
ValueError: If the JSON object is missing a required field.
TypeError: If a value is of the wrong type.
"""
try:
# Example processing: Check for required field and type
if "name" not in json_obj:
raise ValueError("Missing 'name' field")
if not isinstance(json_obj["age"], int):
raise TypeError("Age must be an integer")
# Simulate some processing
processed_data = {"name": json_obj["name"].upper(), "age": json_obj["age"] * 2, "processed_index": index}
return processed_data
except (ValueError, TypeError) as e:
raise e # re-raise the exception to be caught in process_json_batch
except Exception as e:
raise e # re-raise other exceptions
if __name__ == '__main__':
# Example usage
json_data = [
{"name": "Alice", "age": 30},
{"name": "Bob", "age": "25"}, # Simulate a type error
{"age": 40}, # Simulate missing required field
{"name": "Charlie", "age": 22}
]
results = process_json_batch(json_data)
print("\nResults:")
for result in results:
print(result)
Add your comment