Skip to content

json_tools

Class info

Re-exported classes

Class Module Description
JsonDumpError anyenv.json_tools.base Unified exception for all JSON serialization errors.
JsonLoadError anyenv.json_tools.base Unified exception for all JSON parsing errors.
OrJsonProvider anyenv.json_tools.orjson_provider.provider OrJSON implementation of the JSON provider interface.
ParseErrorInfo anyenv.parse_errors Structured information about a parse error.

🛈 DocStrings

Package for JSON-related tools with validation support.

Provides a unified interface for JSON serialization/deserialization with automatic selection of the best available backend and type validation.

JsonDumpError

Bases: Exception

Unified exception for all JSON serialization errors.

Source code in src/anyenv/json_tools/base.py
class JsonDumpError(Exception):
    """Unified exception for all JSON serialization errors."""

JsonLoadError

Bases: Exception

Unified exception for all JSON parsing errors.

Source code in src/anyenv/json_tools/base.py
class JsonLoadError(Exception):
    """Unified exception for all JSON parsing errors."""

    def __init__(
        self,
        message: str,
        *,
        line: int | None = None,
        column: int | None = None,
        source_path: str | Path | None = None,
        source_content: str | None = None,
    ) -> None:
        super().__init__(message)
        self.info = ParseErrorInfo(
            message=message,
            format_name="JSON Parse",
            line=line,
            column=column,
            source_path=source_path,
            source_content=source_content,
        )

    @property
    def line(self) -> int | None:
        """Line number where the error occurred."""
        return self.info.line

    @property
    def column(self) -> int | None:
        """Column number where the error occurred."""
        return self.info.column

    @property
    def source_path(self) -> str | Path | None:
        """Path to the source file that caused the error."""
        return self.info.source_path

    @property
    def source_content(self) -> str | None:
        """Source content that caused the error."""
        return self.info.source_content

    def format(self, context_lines: int = 2, use_color: bool = True) -> str:
        """Format error with source context for display.

        Args:
            context_lines: Number of lines to show before/after the error line.
            use_color: Whether to include ANSI color codes.
        """
        return self.info.format(context_lines=context_lines, use_color=use_color)

column property

column: int | None

Column number where the error occurred.

line property

line: int | None

Line number where the error occurred.

source_content property

source_content: str | None

Source content that caused the error.

source_path property

source_path: str | Path | None

Path to the source file that caused the error.

format

format(context_lines: int = 2, use_color: bool = True) -> str

Format error with source context for display.

Parameters:

Name Type Description Default
context_lines int

Number of lines to show before/after the error line.

2
use_color bool

Whether to include ANSI color codes.

True
Source code in src/anyenv/json_tools/base.py
def format(self, context_lines: int = 2, use_color: bool = True) -> str:
    """Format error with source context for display.

    Args:
        context_lines: Number of lines to show before/after the error line.
        use_color: Whether to include ANSI color codes.
    """
    return self.info.format(context_lines=context_lines, use_color=use_color)

ParseErrorInfo dataclass

Structured information about a parse error.

Source code in src/anyenv/parse_errors.py
@dataclass
class ParseErrorInfo:
    """Structured information about a parse error."""

    message: str
    format_name: str = "Parse"
    line: int | None = None
    column: int | None = None
    source_path: str | Path | None = None
    source_content: str | None = None

    def format(
        self,
        context_lines: int = 2,
        use_color: bool = True,
    ) -> str:
        """Format error with source context for display.

        Args:
            context_lines: Number of lines to show before/after the error line.
            use_color: Whether to include ANSI color codes.
        """
        parts: list[str] = []

        # Header with location
        location = str(self.source_path) if self.source_path else "<string>"
        if self.line is not None:
            location += f":{self.line}"
            if self.column is not None:
                location += f":{self.column}"

        if use_color:
            parts.append(f"\x1b[1;31m{self.format_name} Error\x1b[0m at \x1b[1m{location}\x1b[0m")
        else:
            parts.append(f"{self.format_name} Error at {location}")

        parts.append(f"  {self.message}")

        # Source context
        if self.source_content and self.line is not None:
            parts.append("")
            lines = self.source_content.splitlines()
            start = max(0, self.line - 1 - context_lines)
            end = min(len(lines), self.line + context_lines)

            line_num_width = len(str(end))

            for i in range(start, end):
                line_num = i + 1
                line_content = lines[i] if i < len(lines) else ""
                prefix = ">" if line_num == self.line else " "

                if use_color and line_num == self.line:
                    parts.append(
                        f"\x1b[1;31m{prefix} {line_num:>{line_num_width}} │\x1b[0m {line_content}"
                    )
                else:
                    parts.append(f"{prefix} {line_num:>{line_num_width}} │ {line_content}")

                # Column indicator
                if line_num == self.line and self.column is not None:
                    indicator_padding = " " * (line_num_width + 4 + self.column - 1)
                    if use_color:
                        parts.append(f"\x1b[1;31m{indicator_padding}^\x1b[0m")
                    else:
                        parts.append(f"{indicator_padding}^")

        return "\n".join(parts)

format

format(context_lines: int = 2, use_color: bool = True) -> str

Format error with source context for display.

Parameters:

Name Type Description Default
context_lines int

Number of lines to show before/after the error line.

2
use_color bool

Whether to include ANSI color codes.

True
Source code in src/anyenv/parse_errors.py
def format(
    self,
    context_lines: int = 2,
    use_color: bool = True,
) -> str:
    """Format error with source context for display.

    Args:
        context_lines: Number of lines to show before/after the error line.
        use_color: Whether to include ANSI color codes.
    """
    parts: list[str] = []

    # Header with location
    location = str(self.source_path) if self.source_path else "<string>"
    if self.line is not None:
        location += f":{self.line}"
        if self.column is not None:
            location += f":{self.column}"

    if use_color:
        parts.append(f"\x1b[1;31m{self.format_name} Error\x1b[0m at \x1b[1m{location}\x1b[0m")
    else:
        parts.append(f"{self.format_name} Error at {location}")

    parts.append(f"  {self.message}")

    # Source context
    if self.source_content and self.line is not None:
        parts.append("")
        lines = self.source_content.splitlines()
        start = max(0, self.line - 1 - context_lines)
        end = min(len(lines), self.line + context_lines)

        line_num_width = len(str(end))

        for i in range(start, end):
            line_num = i + 1
            line_content = lines[i] if i < len(lines) else ""
            prefix = ">" if line_num == self.line else " "

            if use_color and line_num == self.line:
                parts.append(
                    f"\x1b[1;31m{prefix} {line_num:>{line_num_width}} │\x1b[0m {line_content}"
                )
            else:
                parts.append(f"{prefix} {line_num:>{line_num_width}} │ {line_content}")

            # Column indicator
            if line_num == self.line and self.column is not None:
                indicator_padding = " " * (line_num_width + 4 + self.column - 1)
                if use_color:
                    parts.append(f"\x1b[1;31m{indicator_padding}^\x1b[0m")
                else:
                    parts.append(f"{indicator_padding}^")

    return "\n".join(parts)

dump_json

dump_json(
    data: Any,
    indent: bool = False,
    naive_utc: bool = False,
    serialize_numpy: bool = False,
    sort_keys: bool = False,
    backend: BackendType = "auto",
) -> str

Serialize data to a JSON string.

Parameters:

Name Type Description Default
data Any

The data to serialize

required
indent bool

Whether to format the output with indentation

False
naive_utc bool

Whether to interpret naive datetime objects as UTC

False
serialize_numpy bool

Whether to serialize numpy arrays

False
sort_keys bool

Sort dictionary keys

False
backend BackendType

JSON backend to use for serialization

'auto'

Returns:

Type Description
str

The serialized JSON string

Raises:

Type Description
JsonDumpError

If serialization fails

Source code in src/anyenv/json_tools/__init__.py
def dump_json(
    data: Any,
    indent: bool = False,
    naive_utc: bool = False,
    serialize_numpy: bool = False,
    sort_keys: bool = False,
    backend: BackendType = "auto",
) -> str:
    """Serialize data to a JSON string.

    Args:
        data: The data to serialize
        indent: Whether to format the output with indentation
        naive_utc: Whether to interpret naive datetime objects as UTC
        serialize_numpy: Whether to serialize numpy arrays
        sort_keys: Sort dictionary keys
        backend: JSON backend to use for serialization

    Returns:
        The serialized JSON string

    Raises:
        JsonDumpError: If serialization fails
    """
    provider = get_json_provider(backend)
    return provider.dump_json(
        data,
        indent=indent,
        naive_utc=naive_utc,
        serialize_numpy=serialize_numpy,
        sort_keys=sort_keys,
    )

get_json_provider

get_json_provider(backend: BackendType = 'auto') -> type[JsonProviderBase]

Get the specified JSON provider or the best available one.

Parameters:

Name Type Description Default
backend BackendType

The JSON backend to use. If "auto", uses the best available.

'auto'

Returns:

Type Description
type[JsonProviderBase]

A JSON provider implementation

Raises:

Type Description
ImportError

If the requested backend is not available

Source code in src/anyenv/json_tools/__init__.py
def get_json_provider(backend: BackendType = "auto") -> type[JsonProviderBase]:
    """Get the specified JSON provider or the best available one.

    Args:
        backend: The JSON backend to use. If "auto", uses the best available.

    Returns:
        A JSON provider implementation

    Raises:
        ImportError: If the requested backend is not available
    """
    if backend == "auto":
        return _provider

    if backend == "orjson":
        if importlib.util.find_spec("orjson") is not None:
            from anyenv.json_tools.orjson_provider.provider import OrJsonProvider

            return OrJsonProvider
        msg = "orjson backend requested but not installed"
        raise ImportError(msg)

    if backend == "pydantic":
        if importlib.util.find_spec("pydantic_core") is not None:
            from anyenv.json_tools.pydantic_provider.provider import PydanticProvider

            return PydanticProvider
        msg = "pydantic backend requested but pydantic_core not installed"
        raise ImportError(msg)

    if backend == "msgspec":
        if importlib.util.find_spec("msgspec") is not None:
            from anyenv.json_tools.msgspec_provider.provider import MsgSpecProvider

            return MsgSpecProvider
        msg = "msgspec backend requested but not installed"
        raise ImportError(msg)

    if backend == "stdlib":
        from anyenv.json_tools.stdlib_provider.provider import StdLibProvider

        return StdLibProvider

    msg = f"Unknown backend: {backend}"
    raise ValueError(msg)

load_json

load_json(
    data: str | bytes | TextIOWrapper, return_type: type[T], backend: BackendType = "auto"
) -> T
load_json(
    data: str | bytes | TextIOWrapper, return_type: UnionType, backend: BackendType = "auto"
) -> Any
load_json(
    data: str | bytes | TextIOWrapper, return_type: None = None, backend: BackendType = "auto"
) -> Any
load_json(
    data: str | bytes | TextIOWrapper,
    return_type: type[Any] | UnionType | None = None,
    backend: BackendType = "auto",
) -> Any

Load JSON data with optional type validation.

Parameters:

Name Type Description Default
data str | bytes | TextIOWrapper

The JSON data to parse (string, bytes, or file-like object)

required
return_type type[Any] | UnionType | None

Optional type to validate the data against

None
backend BackendType

JSON backend to use for parsing

'auto'

Returns:

Type Description
Any

The parsed and validated data

Raises:

Type Description
JsonLoadError

If parsing fails

TypeError

If validation against return_type fails

Source code in src/anyenv/json_tools/__init__.py
def load_json(
    data: str | bytes | TextIOWrapper,
    return_type: type[Any] | types.UnionType | None = None,
    backend: BackendType = "auto",
) -> Any:
    """Load JSON data with optional type validation.

    Args:
        data: The JSON data to parse (string, bytes, or file-like object)
        return_type: Optional type to validate the data against
        backend: JSON backend to use for parsing

    Returns:
        The parsed and validated data

    Raises:
        JsonLoadError: If parsing fails
        TypeError: If validation against return_type fails
    """
    provider = get_json_provider(backend)
    parsed_data = provider.load_json(data)

    if return_type is not None:
        from anyenv.validate import validate_json_data

        return validate_json_data(parsed_data, return_type)
    return parsed_data