"""JSON format converter.""" import json from pathlib import Path from typing import Any, Dict, Union from config_converter.converters.base import BaseConverter, ConversionError class JsonConverter(BaseConverter): """Converter for JSON configuration files.""" FORMAT_NAME = "json" FILE_EXTENSIONS = ["json"] def read(self, source: Union[str, Path]) -> Dict[str, Any]: """Read and parse a JSON configuration file.""" try: with open(source, "r", encoding="utf-8") as f: data = json.load(f) return data if data is not None else {} except json.JSONDecodeError as e: raise ConversionError(f"Invalid JSON in {source}: {e}") from e except FileNotFoundError as e: raise ConversionError(f"File not found: {source}") from e except PermissionError as e: raise ConversionError(f"Permission denied: {source}") from e def write(self, data: Dict[str, Any], target: Union[str, Path]) -> None: """Write configuration data to a JSON file.""" try: with open(target, "w", encoding="utf-8") as f: json.dump(data, f, indent=2, ensure_ascii=False) except (OSError, TypeError) as e: raise ConversionError(f"Failed to write JSON to {target}: {e}") from e def parse(self, content: str) -> Dict[str, Any]: """Parse JSON content from a string.""" try: data = json.loads(content) return data if data is not None else {} except json.JSONDecodeError as e: raise ConversionError(f"Invalid JSON content: {e}") from e def format(self, data: Dict[str, Any]) -> str: """Format configuration data to a JSON string.""" try: return json.dumps(data, indent=2, ensure_ascii=False) except (TypeError, ValueError) as e: raise ConversionError(f"Failed to format data as JSON: {e}") from e