From 46e52b23eece9b07157859d69bd6d4ee94d25987 Mon Sep 17 00:00:00 2001 From: 7000pctAUTO Date: Wed, 4 Feb 2026 21:54:21 +0000 Subject: [PATCH] Add source code files --- config_converter/converters/json_converter.py | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) create mode 100644 config_converter/converters/json_converter.py diff --git a/config_converter/converters/json_converter.py b/config_converter/converters/json_converter.py new file mode 100644 index 0000000..b77e0e4 --- /dev/null +++ b/config_converter/converters/json_converter.py @@ -0,0 +1,48 @@ +"""JSON format converter.""" + +import json +from pathlib import Path +from typing import Any, Dict + +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: str | Path) -> Dict[str, Any]: + """Read and parse a JSON configuration file.""" + try: + with open(source, "r", encoding="utf-8") as f: + return json.load(f) + 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: 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: + return json.loads(content) + 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