diff --git a/src/testdatagen/formatters/json_formatter.py b/src/testdatagen/formatters/json_formatter.py new file mode 100644 index 0000000..bbaf88d --- /dev/null +++ b/src/testdatagen/formatters/json_formatter.py @@ -0,0 +1,57 @@ +"""JSON output formatter.""" + +import json +from typing import Any, Dict, List, Optional + + +class JSONFormatter: + """Formatter that outputs data in JSON format.""" + + def __init__(self, indent: Optional[int] = None, ensure_ascii: bool = False): + """Initialize the JSON formatter. + + Args: + indent: Number of spaces for indentation (None for no indentation) + ensure_ascii: Whether to escape non-ASCII characters + """ + self.indent = indent + self.ensure_ascii = ensure_ascii + + def format(self, records: List[Dict[str, Any]]) -> str: + """Format records as JSON string. + + Args: + records: List of data records to format + + Returns: + JSON-formatted string + """ + if len(records) == 1: + return json.dumps( + records[0], + indent=self.indent, + ensure_ascii=self.ensure_ascii, + default=self._json_serializer + ) + + return json.dumps( + records, + indent=self.indent, + ensure_ascii=self.ensure_ascii, + default=self._json_serializer + ) + + def _json_serializer(self, obj: Any) -> Any: + """Custom JSON serializer for objects not serializable by default. + + Args: + obj: Object to serialize + + Returns: + Serialized representation + """ + if hasattr(obj, '__dict__'): + return obj.__dict__ + if hasattr(obj, 'isoformat'): + return obj.isoformat() + return str(obj) \ No newline at end of file