import json
from typing import Any, Dict, List, Union
def nest_api_response(data: Dict[str, Any], dry_run: bool = False) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
"""
Nests API response structures with optional dry-run mode.
Args:
data: The API response data (dict or list).
dry_run: If True, only prints the structure without modifying it.
Returns:
Nested data structure.
"""
if dry_run:
print("Dry run mode: Printing structure only.")
print(json.dumps(data, indent=4))
return data # Return original data for consistency
if isinstance(data, dict):
nested_data = {}
for key, value in data.items():
nested_data[key] = nest_api_response(value, dry_run)
return nested_data
elif isinstance(data, list):
nested_data = []
for item in data:
nested_data.append(nest_api_response(item, dry_run))
return nested_data
else:
return data
if __name__ == '__main__':
# Example usage
api_response = {
"status": "success",
"code": 200,
"data": {
"user": {
"id": 123,
"name": "John Doe",
"email": "john.doe@example.com"
},
"posts": [
{"id": 1, "title": "First Post"},
{"id": 2, "title": "Second Post"}
]
}
}
print("Original API Response:")
print(json.dumps(api_response, indent=4))
nested_response = nest_api_response(api_response)
print("\nNested API Response:")
print(json.dumps(nested_response, indent=4))
# Dry run example
nested_response_dry = nest_api_response(api_response, dry_run=True)
print("\nDry Run Output:")
print(nested_response_dry)
Add your comment