import json
import time
import random
def clean_json_data(json_string, max_retries=3, retry_interval=2):
"""
Cleans data from a JSON string with retry logic.
For development use only.
Args:
json_string (str): The JSON string to clean.
max_retries (int): Maximum number of retries.
retry_interval (int): Retry interval in seconds.
Returns:
dict or None: The cleaned JSON data as a dictionary, or None if cleaning fails after max retries.
"""
for attempt in range(max_retries):
try:
data = json.loads(json_string) # Parse the JSON
return data # Return if parsing is successful
except json.JSONDecodeError as e:
if attempt < max_retries - 1:
wait_time = retry_interval + random.uniform(0, retry_interval / 2) # Add some randomness to retry
print(f"Error decoding JSON (attempt {attempt + 1}/{max_retries}): {e}. Retrying in {wait_time:.2f} seconds...")
time.sleep(wait_time)
else:
print(f"Error decoding JSON after {max_retries} attempts: {e}")
return None # Return None if all retries fail
if __name__ == '__main__':
# Example usage
sample_json = '{"name": "John Doe", "age": 30, "city": "New York", "invalid_field": "missing"}'
cleaned_data = clean_json_data(sample_json)
if cleaned_data:
print("Cleaned data:")
print(cleaned_data)
else:
print("Failed to clean data.")
Add your comment