Source code for automated_document_parser.loaders.file_load.json_loader

"""JSON loader with optional jq-based query support."""

import json

from langchain_core.documents import Document

from .base import BaseFileLoader


[docs] class JSONFileLoader(BaseFileLoader): """Load JSON using the standard library, with optional jq expressions."""
[docs] def load(self) -> list[Document]: """Load JSON values selected by ``jq_schema`` as documents.""" try: with self.file_path.open( encoding=self.kwargs.get("encoding", "utf-8") ) as file: data = json.load(file) except (OSError, UnicodeError, json.JSONDecodeError) as exc: raise RuntimeError( f"Failed to load JSON file {self.file_path}: {exc}" ) from exc jq_schema = self.kwargs.get("jq_schema", ".") text_content = self.kwargs.get("text_content", False) if jq_schema == ".": values = [data] else: try: import jq except ImportError as exc: raise ImportError( "Custom jq_schema queries require the JSON extra. " "Install with: pip install 'automated-document-parser[json]'" ) from exc values = jq.compile(jq_schema).input_value(data).all() documents = [] for value in values: content = ( value if text_content and isinstance(value, str) else json.dumps(value, ensure_ascii=False, indent=2) ) documents.append( Document( page_content=content, metadata={"source": str(self.file_path)}, ) ) return documents
[docs] @staticmethod def get_install_command() -> str: """Return the optional installation command for jq expressions.""" return "pip install 'automated-document-parser[json]'"