Add source code files
Some checks failed
CI / test (push) Has been cancelled

This commit is contained in:
2026-02-04 21:54:21 +00:00
parent 2c64d34428
commit 46e52b23ee

View File

@@ -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