From 7d430f687b9787c9fcb8ee08b943b661bdb9ce91 Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Sun, 22 Mar 2026 19:45:30 +0000 Subject: [PATCH] Initial upload: testdata-cli with CI/CD workflow --- src/testdatagen/formatters/json_formatter.py | 57 ++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/testdatagen/formatters/json_formatter.py 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