import json
def convert_api_response(response_data, target_format, overrides=None):
"""
Converts API response data to a specified format with manual overrides.
Args:
response_data (dict): The API response data as a dictionary.
target_format (str): The desired output format ('json', 'dict', 'list').
overrides (dict, optional): A dictionary of key-value pairs to override
values during conversion. Defaults to None.
Returns:
str or list: The converted data in the specified format, or None if conversion fails.
"""
if response_data is None:
return None
try:
if target_format == 'json':
return json.dumps(response_data, indent=4) # Serialize to JSON with indentation
elif target_format == 'dict':
# Return as a dictionary, preserving the original structure
return response_data
elif target_format == 'list':
#Convert to list, handling nested data.
if isinstance(response_data, dict):
return list(response_data.values())
elif isinstance(response_data, list):
return response_data
else:
return [response_data] #Handle single values as a list
else:
print(f"Error: Unsupported target format: {target_format}")
return None
except Exception as e:
print(f"Error during conversion: {e}")
return None
if __name__ == '__main__':
# Example Usage
api_response = {
"user_id": 123,
"username": "john_doe",
"email": "john.doe@example.com",
"profile": {
"first_name": "John",
"last_name": "Doe",
"age": 30
}
}
# Convert to JSON
json_output = convert_api_response(api_response, 'json')
print("JSON Output:\n", json_output)
# Convert to dictionary (no change in this case)
dict_output = convert_api_response(api_response, 'dict')
print("\nDictionary Output:\n", dict_output)
# Convert to list
list_output = convert_api_response(api_response, 'list')
print("\nList Output:\n", list_output)
#Example with overrides
overrides = {"user_id": 456, "email": "new_email@example.com"}
converted_response = convert_api_response(api_response, 'json', overrides)
print("\nJSON Output with overrides:\n", converted_response)
Add your comment