Initial upload: testdata-cli with CI/CD workflow
This commit is contained in:
57
src/testdatagen/formatters/json_formatter.py
Normal file
57
src/testdatagen/formatters/json_formatter.py
Normal file
@@ -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)
|
||||
Reference in New Issue
Block a user