1. import json
  2. from typing import Any, Dict, List, Union
  3. def nest_api_response(data: Dict[str, Any], dry_run: bool = False) -> Union[Dict[str, Any], List[Dict[str, Any]]]:
  4. """
  5. Nests API response structures with optional dry-run mode.
  6. Args:
  7. data: The API response data (dict or list).
  8. dry_run: If True, only prints the structure without modifying it.
  9. Returns:
  10. Nested data structure.
  11. """
  12. if dry_run:
  13. print("Dry run mode: Printing structure only.")
  14. print(json.dumps(data, indent=4))
  15. return data # Return original data for consistency
  16. if isinstance(data, dict):
  17. nested_data = {}
  18. for key, value in data.items():
  19. nested_data[key] = nest_api_response(value, dry_run)
  20. return nested_data
  21. elif isinstance(data, list):
  22. nested_data = []
  23. for item in data:
  24. nested_data.append(nest_api_response(item, dry_run))
  25. return nested_data
  26. else:
  27. return data
  28. if __name__ == '__main__':
  29. # Example usage
  30. api_response = {
  31. "status": "success",
  32. "code": 200,
  33. "data": {
  34. "user": {
  35. "id": 123,
  36. "name": "John Doe",
  37. "email": "john.doe@example.com"
  38. },
  39. "posts": [
  40. {"id": 1, "title": "First Post"},
  41. {"id": 2, "title": "Second Post"}
  42. ]
  43. }
  44. }
  45. print("Original API Response:")
  46. print(json.dumps(api_response, indent=4))
  47. nested_response = nest_api_response(api_response)
  48. print("\nNested API Response:")
  49. print(json.dumps(nested_response, indent=4))
  50. # Dry run example
  51. nested_response_dry = nest_api_response(api_response, dry_run=True)
  52. print("\nDry Run Output:")
  53. print(nested_response_dry)

Add your comment