1. import json
  2. import time
  3. import random
  4. def clean_json_data(json_string, max_retries=3, retry_interval=2):
  5. """
  6. Cleans data from a JSON string with retry logic.
  7. For development use only.
  8. Args:
  9. json_string (str): The JSON string to clean.
  10. max_retries (int): Maximum number of retries.
  11. retry_interval (int): Retry interval in seconds.
  12. Returns:
  13. dict or None: The cleaned JSON data as a dictionary, or None if cleaning fails after max retries.
  14. """
  15. for attempt in range(max_retries):
  16. try:
  17. data = json.loads(json_string) # Parse the JSON
  18. return data # Return if parsing is successful
  19. except json.JSONDecodeError as e:
  20. if attempt < max_retries - 1:
  21. wait_time = retry_interval + random.uniform(0, retry_interval / 2) # Add some randomness to retry
  22. print(f"Error decoding JSON (attempt {attempt + 1}/{max_retries}): {e}. Retrying in {wait_time:.2f} seconds...")
  23. time.sleep(wait_time)
  24. else:
  25. print(f"Error decoding JSON after {max_retries} attempts: {e}")
  26. return None # Return None if all retries fail
  27. if __name__ == '__main__':
  28. # Example usage
  29. sample_json = '{"name": "John Doe", "age": 30, "city": "New York", "invalid_field": "missing"}'
  30. cleaned_data = clean_json_data(sample_json)
  31. if cleaned_data:
  32. print("Cleaned data:")
  33. print(cleaned_data)
  34. else:
  35. print("Failed to clean data.")

Add your comment