1. import json
  2. def convert_api_response(response_data, target_format, overrides=None):
  3. """
  4. Converts API response data to a specified format with manual overrides.
  5. Args:
  6. response_data (dict): The API response data as a dictionary.
  7. target_format (str): The desired output format ('json', 'dict', 'list').
  8. overrides (dict, optional): A dictionary of key-value pairs to override
  9. values during conversion. Defaults to None.
  10. Returns:
  11. str or list: The converted data in the specified format, or None if conversion fails.
  12. """
  13. if response_data is None:
  14. return None
  15. try:
  16. if target_format == 'json':
  17. return json.dumps(response_data, indent=4) # Serialize to JSON with indentation
  18. elif target_format == 'dict':
  19. # Return as a dictionary, preserving the original structure
  20. return response_data
  21. elif target_format == 'list':
  22. #Convert to list, handling nested data.
  23. if isinstance(response_data, dict):
  24. return list(response_data.values())
  25. elif isinstance(response_data, list):
  26. return response_data
  27. else:
  28. return [response_data] #Handle single values as a list
  29. else:
  30. print(f"Error: Unsupported target format: {target_format}")
  31. return None
  32. except Exception as e:
  33. print(f"Error during conversion: {e}")
  34. return None
  35. if __name__ == '__main__':
  36. # Example Usage
  37. api_response = {
  38. "user_id": 123,
  39. "username": "john_doe",
  40. "email": "john.doe@example.com",
  41. "profile": {
  42. "first_name": "John",
  43. "last_name": "Doe",
  44. "age": 30
  45. }
  46. }
  47. # Convert to JSON
  48. json_output = convert_api_response(api_response, 'json')
  49. print("JSON Output:\n", json_output)
  50. # Convert to dictionary (no change in this case)
  51. dict_output = convert_api_response(api_response, 'dict')
  52. print("\nDictionary Output:\n", dict_output)
  53. # Convert to list
  54. list_output = convert_api_response(api_response, 'list')
  55. print("\nList Output:\n", list_output)
  56. #Example with overrides
  57. overrides = {"user_id": 456, "email": "new_email@example.com"}
  58. converted_response = convert_api_response(api_response, 'json', overrides)
  59. print("\nJSON Output with overrides:\n", converted_response)

Add your comment