Created
April 28, 2024 08:26
-
-
Save 2tony2/124d0d00a4a58c26288e4c1f4958cc57 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from abc import ABC, abstractmethod | |
class DataFormatter(ABC): | |
@staticmethod | |
@abstractmethod | |
def format_data(data): | |
"""Define a standard way to format data.""" | |
pass | |
class JSONFormatter(DataFormatter): | |
@staticmethod | |
def format_data(data): | |
"""Format data as JSON.""" | |
import json | |
return json.dumps(data, ensure_ascii=False) | |
class CSVFormatter(DataFormatter): | |
@staticmethod | |
def format_data(data): | |
"""Format data as CSV.""" | |
import csv | |
from io import StringIO | |
output = StringIO() | |
writer = csv.DictWriter(output, fieldnames=data[0].keys()) | |
writer.writeheader() | |
writer.writerows(data) | |
return output.getvalue() | |
# Usage example | |
if __name__ == "__main__": | |
# Example data | |
data_dict = {"name": "Alice", "age": 30, "city": "New York"} | |
data_list = [ | |
{"name": "Alice", "age": 30, "city": "New York"}, | |
{"name": "Bob", "age": 25, "city": "Los Angeles"} | |
] | |
# Format as JSON | |
json_data = JSONFormatter.format_data(data_dict) | |
print("JSON Formatted Data:") | |
print(json_data) | |
# Format as CSV | |
csv_data = CSVFormatter.format_data(data_list) | |
print("CSV Formatted Data:") | |
print(csv_data) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment